96. Longest Stretch to K

A river gauge records the net change in water level for each hour of a long storm. The array nums holds those changes in order: positive values are rises, negative values are drops, and zero means no change.

Given the integer k, find the longest run of consecutive hours whose changes add up to exactly k, and return the number of hours in that run. A run must contain at least one hour. If no run of consecutive hours adds up to k, return 0.

Example 1

Input:
nums = [2,-1,4,-3,1], k = 3
Output:
5
Explanation:

The run [2, -1, 4, -3, 1] sums to 3 and spans all 5 hours, so the answer is 5.

Example 2

Input:
nums = [4,6,8], k = 5
Output:
0
Explanation:

No run of consecutive values sums to 5, so the answer is 0.

Constraints

  • 1 ≤ nums.length ≤ 200000
  • -104 ≤ nums[i] ≤ 104
  • -109 ≤ k ≤ 109

Individual values may be negative, so a two-pointer window does not work directly.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…