Find the largest continuous sequence in a array which sums to zero.
Example:
Input: {1 ,2 ,-2 ,4 ,-4}
Output: {2 ,-2 ,4 ,-4}
NOTE : If there are multiple correct answers, return the sequence which occurs first in the array.
Method:
Lets try to reduce the problem to a much simpler problem. Lets say we have another array sum where
sum[i] = Sum of all elements from A[0] to A[i] Note that in this array, sum of elements from A[i] to A[j] = Sum[j] - Sum[i-1]
We need to find j and i such that sum of elements from A[i] to A[j] = 0 Or Sum[j] - Sum[i-1] = 0 Or Sum[j] = Sum[i-1] Now, the problem reduces to finding 2 indices i and j such that sum[i] = sum[j] How can you solve the above problem ?
Solution:
Time: O(n) Space: O(n)
public class Solution { static class Pair { int x; int y;
public Pair(int x, int y) { this.x = x; this.y = y; } }
public ArrayList<Integer> lszero(ArrayList<Integer> A) { int[] sum = new int[A.size()]; for (int i = 0; i < A.size(); i ++) { if (i == 0) { sum[i] = A.get(i); } else { sum[i] = A.get(i) + sum[i - 1]; } } Map<Integer, Pair> map = new HashMap<>(); for (int i = 0; i < sum.length; i ++) { if (map.containsKey(sum[i])) { Pair p = map.get(sum[i]); p.x = Math.min(p.x, i); p.y = Math.max(p.y, i); } else { Pair p = new Pair(i, i); map.put(sum[i], p); } } int min = Integer.MAX_VALUE; int max = Integer.MAX_VALUE; for (Map.Entry<Integer, Pair> entry : map.entrySet()) { Pair p = entry.getValue(); // System.out.println(entry.getKey() + ": <" + p.x + ", " + p.y + ">"); if (p.y - p.x > max - min || (p.y - p.x == max - min && p.x < min)) { min = p.x; max = p.y; } // System.out.println("min max: <" + min + ", " + max + ">"); } if (map.containsKey(0)) { Pair p = map.get(0); if (p.y + 1 >= max - min) { min = -1; max = p.y; } } return new ArrayList<Integer>(A.subList(min + 1, max + 1)); } }