Given an array of positive and negative integers find the first subarray with zero sum

Q:

Given an array of positive and negative integers find the first subarray with zero sum?

no 0's will be a part of the input array and handle all the edge cases

A:

1. iterate through the array once, and take the sum from 0 to every other index of the array.
2. If any sum is zero, the subarray from 0 to that index is the first such subarray.
else
3. In the sum, if any two numbers are same, then the subarray between those two index (i+1, j) is the first such subarray to have a sum zero.

The algo works o(n). Two iterations are required.

e.g.

array = {1,2,3,-1,-2,4,1,-5,6};

array2={1,3,6,5 , 3, 7,8, 3,9};

so, i = 1, j = 4, the sub array from i+1 to j {3, -1, -2} is the answer. 

原文地址:https://www.cnblogs.com/yayagamer/p/2560255.html