1298. Shortest Wide Stretch

A hiker logs the altitude at every checkpoint of a trail and stores the values in the array nums. A section of consecutive checkpoints is called steep when the highest altitude in it minus the lowest altitude in it is at least gap. Return the number of checkpoints in the shortest steep section, where a section is any non-empty contiguous subarray of nums, or return -1 if no section is steep.

A single checkpoint has a spread of 0, so when gap is 0 the answer is 1. Several sections may tie for the shortest length, but only that length is returned. The array can hold up to 200000 values, so aim for O(n) time and O(n) extra space.

Example 1

Input:
nums = [4,4,5,9,6], gap = 4
Output:
2
Explanation:

The adjacent pair (5, 9) has a spread of 4, and no single element reaches a spread of 4, so the shortest steep section has length 2.

Example 2

Input:
nums = [1,2,3,4], gap = 10
Output:
-1
Explanation:

The largest possible spread is 4 - 1 = 3, which never reaches 10, so the answer is -1.

Example 3

Input:
nums = [1,3,2,3,5], gap = 3
Output:
3
Explanation:

No pair has a spread of 3, but the section (2, 3, 5) has spread 3, so the shortest length is 3.

Constraints

  • 1 ≤ n ≤ 2 * 105, where n is the length of nums
  • 0 ≤ nums[i] ≤ 109
  • 0 ≤ gap ≤ 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 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…