Find shortest subarray with range ≥ k
MetaSoftware Engineer · OnsiteLast updated
This question evaluates proficiency with array algorithms and range-query reasoning, testing understanding of max/min behavior over contiguous subarrays and use of appropriate data-structure techniques; it belongs to the Coding & Algorithms domain.
Problem
You are given an integer array nums of length n and an integer k.
Define the range of a subarray as:
[ \max(\text{subarray}) - \min(\text{subarray}) ]
Return the length of the shortest non-empty contiguous subarray whose range is at least k.
If no such subarray exists, return -1.
Input
nums: array of integers (can include negatives)k: non-negative integer
Output
- An integer: the minimum length of a qualifying subarray, or
-1if none exists.
Constraints (typical interview scale)
1 <= n <= 2 * 10^5-10^9 <= nums[i] <= 10^90 <= k <= 10^9
Examples
nums = [1, 3, 2], k = 2→ answer2(subarray[1,3]has range2)nums = [5, 5, 5], k = 1→ answer-1
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.