Given an array of integers. Find out its longest sub-array (contiguous subsequence) whose sum is 0.
The sub-array for output may be an empty array.
Input
Input an array of integers.
Output
Output the longest zero sum sub-array. If there are multiple such arrays, output any one of them.
Output Format
You may output in one of following acceptable format:
- Output an array of integers;
- Output the index of first (inclusive) and last (inclusive) element of sub-array;
- Output (last = first - 1) for empty sub-array
- Output the index of first (inclusive) and last (exclusive) element of sub-array;
- Output the index of first (inclusive) element and length of sub-array;
You may choose 0-indexed or 1-indexed value for 2~4 options. But your choices should be consistent for both first and last element.
Rules
- This is code golf, shortest codes win.
- As usual, standard loopholes are forbidden.
- Your program may fail due to integer overflow (as long as this not trivialize this challenge, which is a standard loophole).
- This is code golf. We don't care the performance of your algorithm / implementation.
Testcases
Input -> Output
[] -> []
[0] -> [0]
[1] -> []
[-1,1] -> [-1,1]
[-1,1,2] -> [-1,1]
[-2,-1,1,2] -> [-2,-1,1,2]
[1,2,3,4,5] -> []
[1,0,2,0,3,0] -> [0]
[1,2,-2,3,-4,5] -> [1,2,-2,3,-4]
[1,2,3,4,5,-4,-3,-2,-1,0] -> [4,5,-4,-3,-2]
[0,1,0,0,0,1] -> [0,0,0]
[0,0,0,1,0,0,1] -> [0,0,0]
[0,0,0,1,0,0,-1] -> [0,0,0,1,0,0,-1]
[-86,14,-36,21,26,-2,-51,-11,38,28] -> [26,-2,-51,-11,38]
[0,70,65,-47,-98,-61,-14,85,-85,92] -> [0,70,65,-47,-98,-61,-14,85]
[4,-4,2,0,4,-2,-2,1,0,1,-4,0,-2,2,2,-4,0,-1,2,1,-4,-2,3,4,3,0,3,2,-4,2,3,3,1,2,3,-3,-4,3,-4,4,0,-3,-1,-5,-4,1,-3,4,-4,2,-1,-4,0,2,-5,-5,2,1,-4,0,-1,4,3,3,-5,-4,-5,3,-3,-1,-5,1,-2,3,0,3,-4,1,-5,-1,4,-5,2,1,-3,4,4,1,-1,-5,-5,-2,4,0,-3,4,1,-3,0,-3] -> [4,-4,2,0,4,-2,-2,1,0,1,-4,0,-2,2,2,-4,0,-1,2,1,-4,-2,3,4,3,0,3,2,-4,2,3,3,1,2,3,-3,-4,3,-4,4,0,-3,-1,-5,-4,1,-3,4,-4]
[0,1,0,0,0,1] -> [0,0,0]
. My initial attempt in Brachylog passed all existing test cases but failed this one. \$\endgroup\$[0,1,0,0,0,1]
, the leftmost zero-sum sublist is[0]
, different from the longest sublist[0,0,0]
. (A shorter example, which I thought of later, is[0,2,-1,1]
.) \$\endgroup\$