1696. Shortest Spread Window

A weather station records nums[i] readings in order. A window is a run of consecutive readings, and its spread is its maximum minus its minimum. Given the threshold k, find the length of the shortest window whose spread is at least k. Return that length, or -1 if no window reaches the threshold. A window of one reading has spread 0, and since k is at least 1 such a window never qualifies. Checking every window is O(n^2); the intended approach moves two pointers and keeps one decreasing and one increasing monotonic deque for the window maximum and minimum, finishing in O(n) time and O(n) space.

Example 1

Input:
nums = [8,3,4,9,1], k = 6
Output:
2
Explanation:

The pair 9 and 1 is a window of two elements with spread 8, and no window of length 1 can have a spread above 0, so the answer is 2.

Example 2

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

All values are equal, so no window ever reaches a spread of 1.

Example 3

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

The windows of length 2 have spreads 4, 3, 4, 3 and the window [1,5,2] has spread 4; the window of length 4 [1,5,2,6] has spread 5, so the answer is 4.

Constraints

1 ≤ nums.length ≤ 2 * 105

0 ≤ nums[i] ≤ 109

1 ≤ k ≤ 109

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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,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…