VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-largest-subarray-with-0-sum/

⇱ Longest Subarray with 0 Sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Subarray with 0 Sum

Last Updated : 28 Jul, 2025

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].

[Naive Approach] Iterating over all subarrays - O(n2) Time and O(1) Space

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.


Output
5

[Expected Approach] Using Hashmap and Prefix Sum - O(n) Time and O(n) Space

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:

  • Initialize a variable prefixSum = 0 and a hashmap firstSeen = {}.
  • Insert 0 into the hashmap with index -1: This handles the case where a subarray starting from index 0 itself has a sum of zero.
  • Traverse the array element by element:
    => Update the running prefix sum.
    => If this prefix sum has not been seen before, store its index in the hashmap.
    => If this prefix sum has been seen before, it means the elements between the previous index (where this sum was first seen) and the current index sum to zero.
    => Update the maximum length accordingly.

Working:


Output
5

Related Articles:

Comment