AlgoInsight

DSA problem

Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

MediumMonotonic QueuePattern: Monotonic Queuetop300AmazonGoogleMicrosoftBloombergMeta

Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit. The absolute difference between any two elements is equivalent to the difference between the max and the min of the subarray.

The key observation is that the validity predicate "max - min <= limit" is monotone: if a window is valid, every sub-window inside it is too. That makes this problem a classic two-pointer sliding-window candidate. The remaining engineering challenge is efficiently tracking the running max and min as the window slides.

The textbook solution uses two monotonic deques. A max-deque stores indices whose values decrease monotonically from front to back (front = max), and a min-deque stores indices whose values increase monotonically from front to back (front = min). Each deque supports amortized O(1) update because every index is pushed and popped at most once.

The algorithm walks a right pointer through the array, pushing each new index into both deques while preserving their monotone shapes. Whenever nums[max_dq.front] - nums[min_dq.front] > limit, we advance the left pointer and drop any front index that falls out of the window. After each step the window [left, right] is valid, so we track right - left + 1 as a candidate for the answer. The total work is O(n) time and O(n) space.

Examples

Example 1
Input: nums = [8,2,4,7], limit = 4
Output: 2
Explanation: The longest valid subarrays are [8,2] (diff 6 invalid), [2,4] diff 2, [4,7] diff 3, [2,4,7] diff 5 invalid. The best valid windows have length 2.
Example 2
Input: nums = [10,1,2,4,7,2], limit = 5
Output: 4
Explanation: The subarray [2,4,7,2] has max 7 and min 2, so max - min = 5 <= 5; it has length 4, which is optimal.
Example 3
Input: nums = [4,2,2,2,4,4,2,2], limit = 0
Output: 3
Explanation: With limit 0 only runs of equal values are allowed. The longest such run is the three consecutive 2s at indices 1, 2, 3.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

sliding-windowmonotonic-queuearraytwo-pointers

Browse all DSA problems