Update appNew update is available. Click here to update.

Longest Subarray Zero Sum

Last Updated: 1 Dec, 2020
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

Ninja loves playing with numbers. So his friend gives him an array on his birthday. The array consists of positive and negative integers. Now Ninja is interested in finding the length of the longest subarray whose sum is zero.

Input Format:
The first line contains a single integer T, denoting the number of test cases. 

The first line of each test case will contain the integer N, denoting the number of elements in the given array.

The second and last line contains N space-separated integers that denote the value of the elements of the array.
Output Format
The first and only line of each test case in the output contains an integer denoting the length of the longest subarray whose sum is zero.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 10
1 <= N <= 10^4
-10^5 <= arr[i] <= 10^5

Time Limit: 1 sec

Approach 1

   We will create the various sub-arrays possible from the given array. We will then eliminate those sub-arrays whose sum is not zero. Out of the remaining sub-arrays, we check the length of each sub-array and see which has the largest length. We will return the largest length as our final answer.

 

The steps are as follows:

  • We initialize ‘maxLen’  to store the length of the maximum subset whose sum is zero.
  • We will iterate over all the elements of the array, i.e., i = 0 to i = N - 1:
    • We initialize ‘currSum’ to store the current sum of the sub-array.
    • We will iterate over all the elements of the array, i.e., j = i to j = N - 1:
      • We will add arr[j] to ‘curSum’ to store the sum of the present sub-array.
      • If ‘currSum’  is zero, store the maximum of ‘maxLen’ and j - i +1 in ‘maxLen’.
  • We will return ‘maxLen’ as the final answer.
Try Problem