Arrays and Hashing Prefix sums

81. Longest Subarray with Sum 0

Medium

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]

Output: 5

Explanation: 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]

Output: 0

Explanation: 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]

Output: 1

Explanation: 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.

nums = [2, -2, 2, -2, 2]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.