Find Longest Subarray with Bounded Absolute Difference
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests the ability to use two pointers alongside auxiliary tracking structures to find the longest contiguous subarray where max−min does not exceed a given threshold.
Longest Subarray with Bounded Spread
You are given a list of integers nums and a non-negative integer limit.
Find the length of the longest contiguous subarray such that the difference between the maximum and minimum values in that subarray is at most limit.
A subarray is a contiguous, non-empty portion of the array.
Constraints
1 <= len(nums) <= 2000-10^6 <= nums[i] <= 10^60 <= limit <= 2 * 10^6- If multiple subarrays tie for the longest length, return the length (any such subarray gives the same answer).
Examples
Example 1
Input: longest_bounded_spread([4, 2, 2, 5, 1, 6, 3], 2)
Output: 3
Example 2
Input: longest_bounded_spread([1, 5, 6, 7, 8, 10, 6, 5, 6], 4)
Output: 5
Example 3
Input: longest_bounded_spread([10], 0)
Output: 1
Hints
Hint 1
Try maintaining a sliding window [left, right] and ask: when does expanding right make the window invalid?
Hint 2
You need the current max and min of the window efficiently. Consider what data structures let you add an element from the right and remove an element from the left while tracking max/min.
Hint 3
Two monotonic deques — one for max, one for min — let you maintain the window's extremes in amortized O(1) per move, giving an overall O(n) solution.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Intuition
We want the longest window [left, right] where max(window) - min(window) <= limit. As we slide right rightward, both the max and min of the window can change, so we need an efficient way to query and update them as the window grows and shrinks.
Two Monotonic Deques
We maintain two deques of indices:
max_dq: indices in decreasing order of their values — the front always holds the index of the current window maximum.min_dq: indices in increasing order of their values — the front always holds the index of the current window minimum.
When we advance right:
- Pop from the back of
max_dqany index whose value is ≤nums[right](they can never be the max again). - Pop from the back of
min_dqany index whose value is ≥nums[right]. - Append
rightto both deques.
If nums[max_dq[0]] - nums[min_dq[0]] > limit, we advance left and evict the front of either deque when its index falls below left.
Correctness
Every window considered is the maximal valid window ending at each right. Because both deques always reflect the true max/min of [left, right], the validity check is exact. We never skip a valid window.
Complexity
- Time: O(n) — each index is appended and removed from each deque at most once.
- Space: O(n) — in the worst case both deques hold all n indices simultaneously.
from typing import List
from collections import deque
def longest_bounded_spread(nums: List[int], limit: int) -> int:
max_dq: deque = deque()
min_dq: deque = deque()
left = 0
best = 0
for right, val in enumerate(nums):
while max_dq and nums[max_dq[-1]] <= val:
max_dq.pop()
max_dq.append(right)
while min_dq and nums[min_dq[-1]] >= val:
min_dq.pop()
min_dq.append(right)
while nums[max_dq[0]] - nums[min_dq[0]] > limit:
left += 1
if max_dq[0] < left:
max_dq.popleft()
if min_dq[0] < left:
min_dq.popleft()
best = max(best, right - left + 1)
return best