KatInterview

Longest Contiguous Subarray with a Target Sum

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashingprefix-sumshash-maparrays

Last updated

Tests prefix-sum reasoning, hash-map lookups, and precise tie-breaking to find the longest subarray summing to exactly k.

Longest Contiguous Subarray with a Target Sum

Given an integer array nums and an integer target, find the longest contiguous subarray whose elements sum to exactly target. Return a list [length, l, r] where l and r are the 0-indexed, inclusive left and right boundaries of that subarray.

Tie-breaking rules:

  • If multiple subarrays share the maximum length, return the one with the smallest l.
  • If two subarrays still tie on both length and l, return the one with the smallest r.

If no valid subarray exists, return [0, -1, -1].


Constraints

  • 0 <= len(nums) <= 200,000
  • -10^5 <= nums[i] <= 10^5
  • -10^9 <= target <= 10^9
  • Elements may be negative, zero, or positive.
  • An empty array or one with no qualifying subarray must return [0, -1, -1].
  • A valid subarray must be non-empty (at least one element).

Examples

Example 1

Input: longest_subarray_target_sum([1, 2, 3, 4, 5], 9)

Output: [3, 1, 3]

Example 2

Input: longest_subarray_target_sum([1, -1, 5, -2, 3], 3)

Output: [4, 0, 3]

Example 3

Input: longest_subarray_target_sum([0, 0, 0, 0], 0)

Output: [4, 0, 3]

Example 4

Input: longest_subarray_target_sum([1, 2, 4], 10)

Output: [0, -1, -1]

Hints

Hint 1

Define prefix sums: P[0] = 0, P[j] = nums[0] + … + nums[j-1]. The sum of nums[l..r] equals P[r+1] − P[l]. So a subarray ending at index r sums to target when P[l] = P[r+1] − target for some l ≤ r.

Hint 2

To maximise length for a fixed right endpoint, you want the smallest possible l. Store a hash map from each prefix-sum value to the earliest index at which it first appeared, and never overwrite an existing entry.

Hint 3

Process the lookup before inserting the current prefix sum into the map. This guarantees every stored index is strictly less than the current position, preventing a zero-length match when target = 0.