Largest Continuous Sequence Zero Sum

Preet Kamal
2 min readOct 1, 2021

Find the largest continuous sequence in a array which sums to zero.

Example:

Input:  {1 ,2 ,-2 ,4 ,-4}
Output: {2 ,-2 ,4 ,-4}

So, the question says,

we have to find the sub sequence in the array whose sum is equal to 0. We have to use a mathematical proof here. If we have a cumulative sum array of the given input. For ex, here it will be

input = [1, 2, -2, 4, -4]
cum_sum = [1, 3, 1, 5, 1]
Now, if we want to get the sum between index 2 and index 3. Math says it will be:
cum_sum[3] - cum_sum[2-1] = 5 - 3 = 2
If we see the input[2:3] = [-2, 4] and its sum is 2.
This means if cum_sum[i] == cum_sum[j], sum of input[i-1: j] will be 0.
Sum between 1 and 4 will be cum_sum[4] - cum_sum[1-1] = 1-1 = 0
We have to find i and j such that cum_sum[i-1] == cum_sum[j].
*******************************************************************
We can verify it manually too.
If we want sum between index 2 and index 3 i.e, cum_sum[3] - cum_sum[2-1 (which is equal to 1)]cum_sum[3] = input[0] + input[1] + input[2] + input[3] -------- i
cum_sum[1] = input[0] + input[1] -------- ii
Subtracting eq (ii) from eq (i):
cum_sum[3] - cum_sum[1] = input[2] + input[3] = -2 + 4 = 2
Doing same thing from cum_sum array = cum_sum[3] - cum_sum[1] = 5 - 3 = 2So we'll use this to get to the answer.

So now what do we need ? A dictionary to store all sum and its index because we have to verify if same sum exists or not and if it does exist, then at which index, start and end pointer to mark the sub array, and a variable to store the cum_sum at each step.

Lets dive into code:

A = [ 1, 2, -3, 3 ]
dic = {0: -1} # -1 index for 0 sum
s = 0
start = 0
end = 0
for i in range(len(A)):
s += A[i]
if s in dic: # Checking if same sum exists in the dictionary or not
if i - dic[s] > end - start: # if length of current subarray is greater than end - start, update end and start
end = i
start = dic[s]
else: # if sum doesnt exist, add it in dictionary
dic[s] = i
print(A[start+1: end+1])

That’s all folks. I have just started writing so my explanation may not be clear. If any question, please ask. Thanks.

--

--