KatInterview

Longest Stretch With Bounded Spread

Stacks & QueuesAuto-graded · 26 test cases
MediumAuto-gradedStacks & Queuessliding-windowmonotonic-dequearrays

Last updated

Find the longest contiguous stretch of an integer list whose largest and smallest values differ by at most a tolerance, using a sliding window with monotonic deques.

You are given a list of integer sensor readings and a non-negative integer tolerance. A stretch is a run of one or more consecutive readings. The spread of a stretch is its largest value minus its smallest value.

Return the length of the longest stretch whose spread is at most the tolerance.

Details:

  • A stretch with a single reading has spread 0, so it is always valid, and the answer is always at least 1.
  • If several stretches tie for the longest length, only that length is returned.
  • With a tolerance of 0, only stretches in which every reading is equal are valid.

Constraints

  • 1 <= len(readings) <= 100000
  • -1000000000 <= readings[i] <= 1000000000
  • 0 <= tolerance <= 1000000000
  • The expected solution runs in roughly linear time. A quadratic scan will be too slow for the largest inputs.

Examples

Example 1

Input: longest_calm_window([8, 2, 4, 7], 4)

Output: 2

Hints

Hint 1

If a stretch has spread at most the tolerance, every smaller stretch inside it does too. That lets you grow the right end and move the left end forward only when needed, and the left end never has to move back.

Hint 2

You need the maximum and minimum of the current window quickly after each step. Recomputing them with max() and min() each time is too slow.

Hint 3

Keep two deques of indices: one with values decreasing from front to back (front is the window max) and one with values increasing (front is the window min). Drop indices from the front when they fall left of the window.