Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit (LeetCode 1438): Solution and Explanation

Medium
Array
Queue
Sliding Window
Heap
Ordered Set
Monotonic Queue

Given an integer array and a limit, return the length of the longest subarray in which no two elements differ by more than the limit.

Intuition

Checking every pair inside a window is wasteful. The largest difference in any window is simply its max minus its min, so the window is valid exactly when max - min <= limit.

If a window is invalid, every wider window around it is invalid too. That is the usual sign for a sliding window: grow on the right, and shrink on the left only when the rule breaks.

The hard part is knowing the max and min after every move. A max deque keeps indices whose values fall from front to back: when a new value arrives, any smaller value behind it can never be the max again, so it is popped. The min deque is the mirror image.

The front of each deque is the current extreme. When the left edge moves past that index, pop it, and the next entry becomes the extreme. Every index is pushed and popped at most once per deque.

Approach: Sliding window with a max deque and a min deque

  1. Create empty deques max_q and min_q, and set left = 0, best = 0.
  2. For each right, pop from the back of max_q while its value is less than nums[right], then append right. Do the same for min_q with greater-than.
  3. While nums[max_q[0]] - nums[min_q[0]] > limit, add one to left, and pop the front of either deque if that index is now less than left.
  4. The window [left, right] is valid. Set best = max(best, right - left + 1).
  5. Return best.

Step-by-step example

nums = [8,2,4,7], limit = 4
  1. Index 0 (8) goes into both deques. The window [8] is valid, so best = 1.
  2. Index 1 (2) pops 8 from the min deque. Now max 8 - min 2 = 6 > 4, so left moves to 1 and index 0 leaves the max deque. The window is [2].
  3. Index 2 (4) pops 2 from the max deque. Max 4 - min 2 = 2, so the window [2,4] is valid and best = 2.
  4. Index 3 (7) pops 4 from the max deque. Max 7 - min 2 = 5 > 4, so left moves to 2 and index 1 leaves the min deque. Max 7 - min 4 = 3, the window [4,7] has length 2, and the answer is 2.

Code: Python, Java, C++

1class Solution:
2    def longestSubarray(self, nums: List[int], limit: int) -> int:
3        max_q = collections.deque()
4        min_q = collections.deque()
5        left = 0
6        best = 0
7        for right in range(len(nums)):
8            while max_q and nums[max_q[-1]] < nums[right]:
9                max_q.pop()
10            max_q.append(right)
11            while min_q and nums[min_q[-1]] > nums[right]:
12                min_q.pop()
13            min_q.append(right)
14            while nums[max_q[0]] - nums[min_q[0]] > limit:
15                left += 1
16                if max_q[0] < left:
17                    max_q.popleft()
18                if min_q[0] < left:
19                    min_q.popleft()
20            best = max(best, right - left + 1)
21        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index is appended to each deque once and removed at most once, and left only moves forward.

Space

O(n)

In the worst case, such as a sorted array, one deque holds every index of the window.

Other approaches

Sorted multiset or two heaps (time O(n log n), space O(n))

Keep the window's values in a sorted structure (TreeMap, multiset, or two lazy-deletion heaps) and read the max and min from it. Simpler to reason about but each move costs a log factor.

Non-shrinking window (time O(n), space O(n))

Use if instead of while when the window is invalid: slide it by one rather than shrinking it. The window never gets smaller, so its final size is the answer.

Check every start (time O(n^2), space O(1))

For each start, extend while tracking a running max and min, and stop when the difference exceeds the limit. Quadratic in the worst case.

Common mistakes

  • Popping equal values from the back. Either choice works if you store indices, but if you store values you must keep duplicates, or the deque loses the extreme when one copy leaves.
  • Moving left past the extreme without popping the deque front, which leaves a stale max or min that is no longer in the window.
  • Using a single deque. The max and the min leave the window at different times, so each needs its own structure.
  • Recording best before the shrinking loop has finished.

Frequently asked questions

Why is max - min enough to check every pair?

Any two elements in the window lie between the min and the max, so their difference is at most max - min. If that is within the limit, every pair is.

Why are the deques monotonic?

When a larger value arrives, every smaller value before it will leave the window earlier and is never larger, so it can never be the max again. Removing those values keeps the max deque decreasing, and its front is always the max.

How does this relate to Sliding Window Maximum?

Sliding Window Maximum uses the same max deque with a fixed window size. Here the window size changes, and a second deque tracks the min.