← Questions

Shortest subarray whose max minus min is at least K

0
MetaCodingLast asked Oct 2025

A coding interview question asked in Meta's AI-enabled coding round, last asked Oct 2025. It tests sliding window and monotonic deque.

Given an integer array and k, return the length of the shortest non-empty contiguous subarray whose largest value minus its smallest value is at least k. Return -1 if there is none.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • shortest_range_at_least(nums: list[int], k: int) -> int

Example

shortest_range_at_least([1, 3, 2], 2)       ->  2     # [1, 3] has range 2
shortest_range_at_least([5, 5, 5], 1)       ->  -1
shortest_range_at_least([1, 4, 2, 6], 5)    ->  4     # only the whole array reaches 6 - 1 = 5
shortest_range_at_least([7], 0)             ->  1     # every subarray has range >= 0

Constraints

  • 1 <= len(nums) <= 2 * 10^5, -10^9 <= nums[i] <= 10^9, 0 <= k <= 10^9.
  • Aim for O(n) or O(n log n).

Clarifying questions

  • Is k = 0 allowed? Then the answer is 1.
  • Do you want the length or the subarray?
  • Can the array be empty?

What a strong answer covers

  • The key fact: a subarray's range only grows when you extend it. So for each right end, find the latest left start whose window still has range at least k. That start never moves backward.
  • Two monotonic deques, one for the window maximum and one for the minimum, give the range in O(1). Two pointers then run in O(n) total.
  • An alternative with a sparse table and binary search per right end, O(n log n), and why the deques are simpler.
  • A brute-force O(n²) solution for testing, and edge cases: k = 0, all values equal, the answer is the whole array.

Follow-ups

  • Return the longest subarray whose range is at most k instead.
  • Count the subarrays whose range is at least k.
  • The values arrive as a stream. Report the shortest qualifying window seen so far.

Where it's asked

  • Meta · AI-enabled coding · Last asked Oct 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

sliding window · monotonic deque

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding