Longest Contiguous Subarray with a Target Sum
Arrays & HashingAuto-graded · 24 test casesLast 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 smallestr.
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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why not a sliding window?
A two-pointer window works when the running sum responds predictably to expanding or shrinking the window. Negative values break that monotonicity, so a window can grow or shrink in any direction without getting closer to the target. Prefix sums handle negatives correctly.
Prefix-sum identity
Define:
P[0] = 0P[j] = nums[0] + … + nums[j-1]
The sum of any subarray nums[l..r] equals P[r+1] − P[l]. That subarray sums to target exactly when P[l] = P[r+1] − target. For a fixed right endpoint r, the longest valid subarray starts at the smallest l satisfying this equation.
Algorithm
- Seed a hash map
firstwith{0: -1}. The entry representsP[0] = 0, occurring "before index 0", so a subarray covering the entire prefix from index 0 is handled correctly. - Scan index
ifrom0ton-1, maintaining a running prefix sum. - At each step, compute
needed = prefix − targetand look it up infirst.- If found,
l = first[needed] + 1andlength = i − first[needed]. Compare against the current best using the tie-breaking rules (longer is better; on a tie, prefer smallerl, then smallerr).
- If found,
- Only after the lookup, insert
prefix → iintofirstif it is not already there. Deferring the insert until after the lookup prevents a zero-length match whentarget = 0.
Why this is correct
Maximality per right endpoint. When processing index i, the map holds the earliest index for every prefix sum seen before i. The lookup therefore returns the leftmost valid start, giving the longest subarray ending at i.
Global optimum. Every subarray ends at some i. The algorithm considers all possible right endpoints, so the global maximum is found.
Tie-breaking. We scan i in increasing order and update only on a strictly better answer (or equal length with a lexicographically smaller (l, r) pair). The first time the maximum length is reached is at the smallest r and therefore the smallest l, satisfying both tie-breaking rules.
Earliest-index invariant. Overwriting an existing map entry would replace a smaller index with a larger one, shortening future matches and potentially violating the tie-breaking rules. The if prefix not in first guard preserves the invariant.
Edge cases
| Situation | Result |
|---|---|
| Empty array | Loop never runs → [0, -1, -1] |
No subarray sums to target | best_length stays 0 → [0, -1, -1] |
target = 0 | Repeated prefix values mark zero-sum segments; lookup-before-insert avoids empty matches |
All zeros, target = 0 | Every prefix equals 0, first[0] = -1 gives l = 0 for each i, so the whole array is returned |
| All negatives | Prefix sums are all distinct; the map handles them correctly |
Entire array sums to target | first[0] = -1 produces l = 0, r = n-1 |
Complexity
- Time: O(n) expected — one hash lookup and at most one insert per element, each O(1) average.
- Space: O(n) — the map stores at most n + 1 distinct prefix-sum values.
In languages with fixed-width integers (C++, Java), prefix sums can reach roughly 2 × 10⁵ × 10⁵ = 2 × 10¹⁰, so 64-bit integers are required. Python's arbitrary-precision integers need no special handling.
Full solution
from typing import List
def longest_subarray_target_sum(nums: List[int], target: int) -> List[int]:
# Maps each prefix-sum value to the earliest index at which it occurred.
# Seeding with {0: -1} represents the empty prefix P[0] = 0 before any
# element is read. An index of -1 means "before the array starts", so
# l = first[needed] + 1 = 0 when the whole prefix sums to target.
first = {0: -1}
prefix = 0
best_length = 0
best_l = -1
best_r = -1
for i, value in enumerate(nums):
prefix += value # prefix == P[i+1]
needed = prefix - target
# Lookup BEFORE insert so every stored index is < i,
# preventing an empty-subarray match when target == 0.
if needed in first:
l = first[needed] + 1
length = i - first[needed] # == i - l + 1
# Update if strictly longer, or same length with a better (l, r).
if (
length > best_length
or (length == best_length and length > 0 and (best_l == -1 or l < best_l))
or (length == best_length and length > 0 and l == best_l and i < best_r)
):
best_length = length
best_l = l
best_r = i
# Only record the first time each prefix sum is seen.
if prefix not in first:
first[prefix] = i
return [best_length, best_l, best_r]