Longest Subarray with Zero Sum

Medium

Given an array A, find the length of the longest subarray which has a sum equal to 0.

Example
A: [3, 0, -1, -2, 3, 0, -2]
Result: 5
Explanation: Longest Subarray with sum 0: [0, -1, -2, 3, 0]

Testing

Input Format

The first line contains an integer ‘T’ denoting the number of test cases.
For each test case, the input has two lines:

  • An integer ‘n’ denoting the length of the array A.
  • n space-separated integers denoting the elements of the array A.

Output Format

For each test case, the output contains a line with one integer denoting the length of the longest subarray with a sum equal to 0.

Sample Input

3
7
3 0 -1 -2 3 0 -2
9
1 2 3 4 5 0 0 -1 1
4
1 -4 2 1

Expected Output

5
4
4

Constraints

1 <= T <= 10
1 <= n <= 105
-109 <= Ai <= 109

Editorial Link: Editorial