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

MediumSliding Window · Monotonic Deque🧩 Queue & Monotonic DequeLeetCode #1438 ↗Updated

Problem

Given an integer array nums and an integer limit, find the length of the longest non-empty contiguous subarray in which the difference between any two elements is at most limit. Equivalently, the subarray's max - min must not exceed limit.
Inputnums = [8,2,4,7], limit = 4Output2 ([2,4] or [4,7])
Inputnums = [10,1,2,4,7,2], limit = 5Output4 ([2,4,7,2])
Inputnums = [4,2,2,2,4,4,2,2], limit = 0Output3

1 ≤ n ≤ 105  ·  1 ≤ nums[i] ≤ 109  ·  0 ≤ limit ≤ 109

Try it yourself

Java
class Solution {
    public int longestSubarray(int[] nums, int limit) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Only the window's max and min matter, and if a window is valid so is every window inside it — so a sliding window works. Two monotonic deques report the current max and min in O(1) as the window slides.
PatternQueue & Monotonic Deque

Instinct Arrival order matters, or you need the max/min of a moving window - reach for a FIFO queue, or a deque of indices kept in sorted order.

Memory hack Old ones leave by the front door, weak ones get bounced out the back - so whoever stands at the front is always the champion.

Open the Queue & Monotonic Deque guide →

Approaches

Brute ForceGrow From Every Start

Time O(n2)Space O(1)

Fix a left end and extend right, updating the running min and max. As soon as max - min exceeds limit, any longer extension is also invalid, so stop and move to the next start.

Java
public int longestSubarray(int[] nums, int limit) {
    int n = nums.length;
    int best = 0;
    for (int i = 0; i < n; i++) {
        int lo = nums[i], hi = nums[i];
        for (int j = i; j < n; j++) {
            lo = Math.min(lo, nums[j]);
            hi = Math.max(hi, nums[j]);
            if (hi - lo > limit) break; // longer windows only get worse
            best = Math.max(best, j - i + 1);
        }
    }
    return best;
}

Easy and correct, but quadratic when most windows stay valid.

At a glance

LevelApproachTimeSpace
Brute ForceGrow From Every StartO(n2)O(1)
BetterSliding Window + Sorted Multiset (TreeMap)O(n log n)O(n)
OptimalSliding Window + Two Monotonic DequesO(n)O(n)
Common pitfalls
  • Checking only neighbouring elements — the condition is on the whole window's max and min.
  • Removing a value from the TreeMap without decrementing counts first — breaks duplicates.
  • Popping the deque fronts by value instead of by index, which mishandles repeated numbers.
Interview tips
  • Restate “all pairs within limit” as max - min ≤ limit immediately.
  • Justify the sliding window: a valid window stays valid when shrunk.
  • Offer the TreeMap version first if the deque details feel risky, then optimise.
Pattern
Sliding window + monotonic deque → longest window whose max/min must satisfy a bound.
My notes saved in this browser