Arrays and Hashing Prefix sums
81. Longest Subarray with Sum 0
You are given an array of integers nums. Return the length of the longest subarray whose elements add up
to 0. If no subarray adds up to 0, return 0.
A subarray is a contiguous sequence of elements from nums. Its length is the number of elements in it.
A single element is a subarray too, so a 0 on its own counts.
Example 1
Input: nums = [6, -2, 3, -4, 1, 2, -1]
5Explanation: Two subarrays add up to 0: [3, -4, 1] and [-2, 3, -4, 1, 2]. The longer one has 5 elements, and it
touches neither end of the array.
Example 2
Input: nums = [-3, 5, 1]
0Explanation: The six subarrays add up to −3, 5, 1, 2, 6 and 3. None of them is 0, so the answer is 0.
Example 3
Input: nums = [8, 0, -3]
1Explanation: The 0 on its own adds up to 0, so the answer is 1. No longer subarray does: [8, 0] adds up to 8 and
[0, -3] to −3.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.