Largest subarray with zero sum
Given an array arr[] of length N, find the length of the longest sub-array with a sum equal to 0.
Examples:
Input: arr[] = {15, -2, 2, -8, 1, 7, 10, 23} Output: 5 Explanation: The longest sub-array with elements summing up-to 0 is {-2, 2, -8, 1, 7}
Input: arr[] = {1, 2, 3} Output: 0 Explanation: There is no subarray with 0 sum
def zero_sum(a: List[int]) -> int:
"""
Space complexity: O(1)
Computational complexity: O(N³) -> two nested loops + sum operator
"""
solution = 0
for i in range(len(a)):
for j in range(i+1, len(a)):
partial_sum = sum(a[i:j])
if partial_sum == 0 and (j - i) > solution:
solution = j - i
return solutiondef zero_sum(a: List[int]) -> int:
"""
Space complexity: O(1)
Computational complexity: O(N²)
"""
solution = 0
for i in range(len(a)):
partial_sum = a[i]
for j in range(i+1, len(a)):
partial_sum += a[j]
if partial_sum == 0 and (j - i) > solution:
solution = j - i
return solution
Last updated
Was this helpful?