![]() |
VOOZH | about |
Given an array arr[] consisting of both positive and negative integers, find the length of the longest subarray whose elements sum is zero.
A subarray is a contiguous part of an array, formed by selecting one or more consecutive elements while maintaining their original order.
Examples:
Input: arr[] = [15, -2, 2, -8, 1, 7, 10]
Output: 5
Explanation: The longest subarray with sum equals to 0 is [-2, 2, -8, 1, 7].Input: arr[] = [1, 2, 3]
Output: 0
Explanation: There is no subarray with 0 sum.Input: arr[] = [1, 0, 3]
Output: 1
Explanation: The longest sub-array with sum equal to 0 is [0].
Table of Content
We try all possible subarrays using two nested loops. For each subarray, we calculate its sum, and if the sum is zero, we update the maximum length accordingly.
5
The idea is based on the observation that for two different indices i and j (where j > i) if the prefix sums Si and Sj are equal, it means that the sum of the elements between indices i+1 and j is zero. This is because:
- Sj - Si = arr[i+1] + arr[i+2] + …... + arr[j]
- If Si = Sj, then: arr[i+1] + arr[i+2] + …... + arr[j] = 0. [ The subarray sum from i+1 to j is 0. ]
Step-by-step approach:
Working:
5
Related Articles: