Longest Subarray with Bounded Pairwise Spread
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests ability to use the two-pointer (sliding window) technique to find the longest contiguous subarray where the difference between the max and min elements stays within a given limit.
Longest Subarray with Bounded Pairwise Spread
You are given a list of integers nums and a non-negative integer limit.
A subarray is valid if the difference between its maximum element and its minimum element is at most limit:
max(subarray) - min(subarray) <= limit
Return the length of the longest valid contiguous subarray. If nums is empty, return 0.
Constraints
0 <= len(nums) <= 2000-10^6 <= nums[i] <= 10^60 <= limit <= 2 * 10^6- All integers in
numsmay not be distinct. - If there are multiple subarrays of the same maximum length, any of them qualifies — only the length is returned.
Examples
Example 1
Input: longest_bounded_spread_subarray([4, 8, 5, 1, 7, 9], 3)
Output: 2
Example 2
Input: longest_bounded_spread_subarray([1, 1, 1, 1], 0)
Output: 4
Example 3
Input: longest_bounded_spread_subarray([], 5)
Output: 0
Hints
Hint 1
Try maintaining a sliding window [left, right] and track the current max and min as you expand right. When the spread exceeds limit, advance left.
Hint 2
Naively recomputing max and min on each window expansion is O(n²). Think about data structures that let you track a running max and running min efficiently as the window shrinks from the left — but even a simple O(n²) inner scan is acceptable for n ≤ 2000.
Hint 3
When you move `left` forward, you only need to keep moving it until max - min <= limit again. Recompute the window's max and min from scratch after each shift if needed for simplicity.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
We use a sliding window (two pointers left and right) and need to efficiently track the maximum and minimum of the current window nums[left..right].
A brute-force approach rescans [left, right] for max/min whenever the window changes — that is O(n²) and acceptable for n ≤ 2000, but we can do O(n) using monotonic deques.
Algorithm
-
Maintain two deques:
max_dq: stores indices in decreasing order ofnumsvalue — the front is always the index of the window's current maximum.min_dq: stores indices in increasing order ofnumsvalue — the front is always the index of the window's current minimum.
-
For each new
right:- Trim the back of
max_dqwhile the back element is ≤nums[right](it can never be a future window maximum), then appendright. - Trim the back of
min_dqwhile the back element is ≥nums[right], then appendright. - While
nums[max_dq[0]] - nums[min_dq[0]] > limit, advanceleftand evict the front of each deque if its index is now outside the window.
- Trim the back of
-
After restoring validity, update
best = max(best, right - left + 1).
Correctness
At every iteration, left is the smallest index such that [left, right] satisfies the spread constraint. Because we only advance left forward, this is a true two-pointer sweep. The monotonic deques guarantee O(1) amortized max/min queries because every index is pushed and popped at most once.
Complexity
- Time: O(n) — each element is inserted and removed from each deque at most once.
- Space: O(n) — deques can hold up to n indices in the worst case.
from collections import deque
def longest_bounded_spread_subarray(nums: list, limit: int) -> int:
if not nums:
return 0
max_dq = deque()
min_dq = deque()
left = 0
best = 0
for right in range(len(nums)):
# Maintain decreasing deque for max
while max_dq and nums[max_dq[-1]] <= nums[right]:
max_dq.pop()
max_dq.append(right)
# Maintain increasing deque for min
while min_dq and nums[min_dq[-1]] >= nums[right]:
min_dq.pop()
min_dq.append(right)
# Shrink window from left until spread is within limit
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