Longest Stretch With Bounded Spread
Stacks & QueuesAuto-graded · 26 test casesLast 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] <= 10000000000 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a sliding window [left, right] and extend right one position at a time. For every right, move left forward just far enough that the window's spread is within the tolerance, then record the window length.
To read the window's maximum and minimum in constant time, keep two deques of indices:
max_idx: values strictly decrease from front to back, so the front is the index of the window maximum.min_idx: values strictly increase from front to back, so the front is the index of the window minimum.
When a new value arrives at right:
- Pop from the back of
max_idxevery index whose value is less than or equal to the new value, then appendright. - Pop from the back of
min_idxevery index whose value is greater than or equal to the new value, then appendright. - While
readings[max_idx[0]] - readings[min_idx[0]] > tolerance, incrementleft, and pop the front of either deque if its index is now smaller thanleft. - Update the answer with
right - left + 1.
Why it is correct
- Deques hold the true extremes. An index is removed from the back of
max_idxonly when a later index with an equal or larger value arrives. Any window that contains the older index also contains the newer one, so the older one can never be the unique maximum again. The same argument holds formin_idx. Indices left of the window are removed from the front. So the fronts are always the window max and min. - The window is the longest valid one ending at
right. Validity is monotone: shrinking a valid window keeps it valid. So the smallest validleftfor a givenrightis never smaller than it was forright - 1, and advancingleftonly as far as needed finds it. - The shrink loop terminates. When
left == right, both fronts point toright, so the spread is 0, which is at most the tolerance.
Complexity
- Time: O(n). Each index is pushed and popped at most once per deque, and
leftmoves forward at mostntimes in total. - Space: O(n) in the worst case, for example a strictly monotone input that keeps one deque full.
Reference solution
from collections import deque
from typing import List
def longest_calm_window(readings: List[int], tolerance: int) -> int:
max_idx = deque() # indices with decreasing values; front = window max
min_idx = deque() # indices with increasing values; front = window min
left = 0
best = 0
for right, value in enumerate(readings):
while max_idx and readings[max_idx[-1]] <= value:
max_idx.pop()
max_idx.append(right)
while min_idx and readings[min_idx[-1]] >= value:
min_idx.pop()
min_idx.append(right)
while readings[max_idx[0]] - readings[min_idx[0]] > tolerance:
left += 1
if max_idx[0] < left:
max_idx.popleft()
if min_idx[0] < left:
min_idx.popleft()
best = max(best, right - left + 1)
return best