KatInterview

Widest Window With an Exact Total in a Signed Sequence

Arrays & HashingAuto-graded · 26 test cases
MediumAuto-gradedArrays & Hashingprefix-sumhash-mapsubarray

Last 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] with a <= 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 0 when 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.