Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

Longest subarray with a given sum

Medium · Target 20 minutes · Arrays and hashing· Type asked at

You're given an integer array nums, which may hold negative numbers and zeros, and an integer k, and I'd like you to return the length of the longest contiguous subarray whose elements add up to exactly k, or 0 if there isn't one anywhere in the array.

Examples

InputOutputWhy
nums = [1, -1, 5, -2, 3], k = 34The first four elements add up to 3, and although the [3] at the very end does as well, it's only one element long.
nums = [-2, -1, 2, 1], k = 12That's [-1, 2] in the middle, which beats the single [1] at the end.
nums = [1, 2, 3], k = 70Even the whole array only reaches 6, so there is nothing to return but 0.

Constraints

  • 1 ≤ n ≤ 2 × 10⁵
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • −10⁹ ≤ k ≤ 10⁹
  • Values may be negative or zero

Hints

Hint 1

Once there are negative numbers in the array, a sliding window has nothing to steer by, so I'd think about prefix sums in the way you would for counting.

Hint 2

A range ending at j adds up to k whenever some earlier prefix equals P[j] − k, so ask yourself which of those earlier prefixes would give you the longest range.

Hint 3

It's the one with the smallest index, so you want to store the first index where each prefix value turns up, leave it alone afterwards, and start the map off with prefix 0 at index −1.

Where people lose marks

  • Overwriting the stored index whenever a prefix value repeats, which still runs without complaint and hands you a range that's too short.
  • Seeding the map with index 0 where it should be −1, so that every range starting at the front of the array comes out one shorter than it really is.
  • Reaching for a sliding window, which with a negative number in the array will miss ranges and won't tell you that it has.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.