Widest Window With an Exact Total in a Signed Sequence
Arrays & HashingAuto-graded · 26 test casesLast updated
Find the longest contiguous run in an integer list (negatives and zeros allowed) whose total equals a target, using prefix sums and a hash map of earliest positions.
You are given a list of integers values and an integer target. Find the widest stretch of consecutive entries whose total is exactly target, and return how many entries it contains. If no stretch has that total, return 0.
Details
- A stretch is a non-empty run of adjacent entries
values[a..b]witha <= b. - Entries can be negative, zero, or positive.
- Only the length is returned. If several stretches tie for the greatest length, the answer is simply that shared length.
- The return value is an integer, and it is
0when nothing matches.
Constraints
1 <= len(values) <= 2 * 10^5-10^4 <= values[i] <= 10^4-10^9 <= target <= 10^9- Every contiguous sum lies in
[-2 * 10^9, 2 * 10^9]. - The solution should be fast enough for the maximum input size, so a quadratic scan over all pairs of endpoints is too slow.
Examples
Example 1
Input: widest_window_with_total([2, -1, 3, 1, -2, 2], 3)
Output: 5
Example 2
Input: widest_window_with_total([1, 2, 3], 7)
Output: 0
Example 3
Input: widest_window_with_total([0, 0, 0], 0)
Output: 3
Hints
Hint 1
Because values can be negative or zero, growing and shrinking a two-pointer window has no valid rule. Think about running totals instead.
Hint 2
If prefix[i] is the sum of the first i+1 entries, the run ending at i and starting after prefix position j sums to prefix[i] - prefix[j]. You need that to equal the target.
Hint 3
For each right end, the longest match uses the earliest earlier prefix with value (current prefix - target). Store each prefix total only the first time it appears, and seed the map with total 0 at index -1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let prefix[i] be the sum of values[0..i], and treat the empty prefix as having sum 0 at index -1. A run from j+1 to i has sum prefix[i] - prefix[j]. So a run ending at i totals target exactly when some earlier prefix equals prefix[i] - target, and its length is i - j.
For a fixed right end i, the length is largest when j is as small as possible. So we scan left to right and keep a dictionary mapping each prefix total to the earliest index where it occurred, seeded with {0: -1}.
At each index:
- Add the current entry to the running total.
- Look up
running - target. If found at indexj, theni - jis a candidate; update the best. - Record
runningin the dictionary only if it is not already there, so earlier indices are never overwritten.
A sliding window does not work here: it relies on the window sum changing monotonically, which fails when entries can be negative or zero.
Why it is correct
- Completeness: every qualifying run corresponds to a pair
j < iwithprefix[j] = prefix[i] - target. The lookup happens beforeiis inserted, and all earlier prefixes are already stored, so the match is found if it exists. The seed-1covers runs that start at index 0. - Optimality: keeping only the first occurrence of each total gives the smallest
jfor each right end, hence the longest run. The maximum over all right ends is the global maximum. - Non-empty: looking up before inserting guarantees
j < i, so every candidate length is at least 1. If nothing matches,beststays0.
Complexity
- Time: O(n), a single pass with O(1) average dictionary operations.
- Space: O(n), in the worst case when all prefix totals are distinct.
Reference solution
def widest_window_with_total(values, target):
earliest = {0: -1}
running = 0
best = 0
for i, x in enumerate(values):
running += x
j = earliest.get(running - target)
if j is not None and i - j > best:
best = i - j
if running not in earliest:
earliest[running] = i
return best