Largest Subarray with Sum 0

243
0

Given an integer array arr of size n, find the length of the longest contiguous subarray whose elements add up to 0. Return 0 if no such subarray exists.

Example 1

Input: arr = [15, -2, 2, -8, 1, 7, 10, 23]
Output: 5
Explanation: The subarray [-2, 2, -8, 1, 7] runs from index 1 to index 5. Its elements add up to 0, and it is the longest subarray with that sum.

Example 2

Input: arr = [2, 10, 4]
Output: 0
Explanation: Every element is positive, so every nonempty subarray has a positive sum.

Brute Force Approach

Generate all possible subarrays using two loops. The outer loop chooses a starting index, and the inner loop extends the subarray one element at a time. Keep a running sum and add each new element as the subarray grows.

For example, if the current subarray is [-2, 2], its sum is 0. Extending it to [-2, 2, -8] only requires adding -8 to the existing sum. This lets us calculate each new sum without adding all the elements again.

Whenever the running sum becomes 0, the current subarray is a zero-sum subarray. Calculate its length and update the maximum length if it is longer than the best one found so far.

Approach

  1. Initialise the maximum length to 0.

  2. For each starting index start, reset the running sum to 0.

  3. Move end from start to the last index, adding arr[end] to the running sum at each step.

  4. If the running sum is 0, calculate the subarray length as end - start + 1.

  5. Update the maximum length if the current subarray is longer.

  6. Return the maximum length after checking all starting indices.

Dry Run

Longest zero sum subarray Brute force

Longest zero sum subarray Brute force

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Find the maximum length of a subarray whose sum is 0.
int maxLen(vector<int>& arr) {
const int n = arr.size();
int maxLength = 0;
// Try every index as the starting position.
for (int start = 0; start < n; ++start) {
// Reset the running sum for each new starting index.
long long sum = 0;
// Extend the subarray one element at a time.
for (int end = start; end < n; ++end) {
// Add the newly included element to the running sum.
sum += arr[end];
// Check whether the current subarray has a zero sum.
if (sum == 0) {
// Calculate the current subarray length.
int length = end - start + 1;
// Update the maximum length if this subarray is longer.
maxLength = max(maxLength, length);
}
}
}
// Return the length of the longest zero-sum subarray.
return maxLength;
}
};
int main() {
Solution sol;
// Example input array.
vector<int> arr = {15, -2, 2, -8, 1, 7, 10, 23};
// Print the maximum length of a zero-sum subarray.
cout << sol.maxLen(arr) << '\n'; // Prints 5.
return 0;
}

Complexity Analysis

Time Complexity: O(N²). There are N(N + 1) / 2 subarrays, and each extension updates the sum in constant time.

Space Complexity: O(1). The solution uses a fixed number of variables.

Optimal Approach

A prefix sum is the sum of all elements from index 0 to the current index. If the same prefix sum appears at two different indices, the elements between those positions must add up to 0, because they have caused no overall change in the sum.

For example, in [15, -2, 2, -8, 1, 7, 10, 23], the prefix sum is 15 at both index 0 and index 5. Therefore, the subarray from index 1 through index 5 sums to 0, and its length is 5 - 0 = 5.

Use a hash map to store each prefix sum and the first index where it appears. Keeping the earliest index gives the longest possible subarray when that sum appears again.

Start the map with {0: -1} to represent the empty prefix before the array. If the running sum becomes 0 at index i, this gives a subarray length of i - (-1) = i + 1, covering all elements from index 0 through i.

Approach

  1. Initialise the prefix sum and maximum length to 0.

  2. Create a hash map and store prefix sum 0 at index -1.

  3. Traverse the array, adding each element to the prefix sum.

  4. If the prefix sum is already in the map at index j, the subarray from j + 1 to the current index sums to 0. Update the maximum length using currentIndex - j.

  5. Otherwise, store the current index as the first occurrence of that prefix sum.

  6. Return the maximum length after scanning the entire array.

Dry Run

Longest zero sum subarray Optimal

Longest zero sum subarray Optimal

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Find the maximum length of a subarray whose sum is 0.
int maxLen(vector<int>& arr) {
// Store the first occurrence of every prefix sum.
// Prefix sum 0 is considered to occur at index -1,
// representing the position before the array starts.
unordered_map<long long, int> sumMap{{0, -1}};
// Stores the cumulative sum from index 0 to the current index.
long long sum = 0;
// Stores the maximum length of a zero-sum subarray found so far.
int maxLength = 0;
// Traverse the array and calculate prefix sums.
for (int i = 0; i < arr.size(); ++i) {
// Add the current element to the prefix sum.
sum += arr[i];
// Check whether this prefix sum has appeared before.
auto it = sumMap.find(sum);
if (it != sumMap.end()) {
// The same prefix sum appeared earlier.
// Therefore, the elements between the previous index
// and the current index have a sum of 0.
//
// Length = current index - previous occurrence index.
maxLength = max(maxLength, i - it->second);
} else {
// This prefix sum has appeared for the first time.
// Store its index so that we can calculate the
// maximum possible subarray length later.
sumMap[sum] = i;
}
}
// Return the length of the longest zero-sum subarray.
return maxLength;
}
};
int main() {
Solution sol;
// Example input array.
vector<int> arr = {15, -2, 2, -8, 1, 7, 10, 23};
// Print the maximum length of a zero-sum subarray.
cout << sol.maxLen(arr) << '\n';
return 0;
}

Complexity Analysis

Time Complexity: O(N) on average. Each element takes a hash map lookup and at most one insertion. In the worst case, hash collisions can make the total time O(N²).

Space Complexity: O(N). The map can hold up to N + 1 distinct prefix sums, including the empty prefix.

Interview follow-up Questions

For a fixed ending index, the earliest matching prefix gives the longest zero-sum subarray. In Example 1, the prefix sum 15 appears at indices 0, 2, and 5. At index 5, using index 0 gives length 5, while using index 2 gives length 3.

HashingArrays

Read Similar Blogs

Comments0