Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Longest run whose spread is at most a limit

Medium · Target 25 minutes · Sliding window· Type asked at

Given an array nums and a non-negative integer limit, return the length of the longest contiguous subarray in which the largest and smallest elements differ by at most limit.

Examples

InputOutputWhy
nums = [8,2,4,7], limit = 42[2,4] or [4,7].
nums = [10,1,2,4,7,2], limit = 54[2,4,7,2].
nums = [4,2,2,2,4,4,2,2], limit = 03Three equal values in a row.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁹
  • 0 ≤ limit ≤ 10⁹

Hints

Hint 1

If a run's spread is within the limit, so is every run inside it. So the variable window applies; the hard part is the test.

Hint 2

You need the maximum and minimum of the window after every step, including after removals from the left.

Hint 3

Keep a deque of indices with decreasing values for the maximum, and one with increasing values for the minimum. Pop from the front when an index leaves the window.

Where people lose marks

  • Storing values instead of indices in the deques: then you cannot tell whether the front has left the window.
  • Shrinking by one step with if: one removal may not bring the spread within the limit.
  • Using a sorted multiset: it works, in O(n log n), and is a fine fallback if you forget the deque.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.