Longest Subarray with Zero Sum

Ninja enjoys working with numbers, and as a birthday challenge, his friend provides him with an array consisting of both positive and negative integers. Ninja is curious to identify the length of the longest subarray within this array that sums to zero.

Input:

The first line contains a single integer T, representing the number of test cases.
The first line of each test case consists of the integer N, which represents the number of elements in the array.
The second line of each test case contains N space-separated integers representing the array's elements.

Output:

A single line for each test case, indicating the integer value of the length of the longest subarray with a sum of zero.

Example:

If T = 2, and the arrays are arr1 = [1, -1, 3, 2, -2, -3, 3] and arr2 = [1, 2, -3, 3, -2, -1, 2], the outputs should be 4 and 5 respectively.

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 10^4
  • -10^5 <= arr[i] <= 10^5
  • Time Limit: 1 sec
AnswerBot
5mo

Find the length of the longest subarray with zero sum in an array of integers.

  • Iterate through the array and keep track of the running sum using a hashmap.

  • If the running sum is seen before, the subarra...read more

Durga Prakash
1y

I solved this problem using hashmaps because of their O(1) search operation. I applied 2 nested loops and then used the hashmap to search for the third element to make the sum zero. Time Complexity of...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Bharti Airtel

Q. What is Android with Java?
Q. What are your skills?
Q. How does Java compare to Python?
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits