Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit (LeetCode 1438): Solution and Explanation
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
- Create empty deques
max_qandmin_q, and setleft = 0,best = 0. - For each
right, pop from the back ofmax_qwhile its value is less thannums[right], then appendright. Do the same formin_qwith greater-than. - While
nums[max_q[0]] - nums[min_q[0]] > limit, add one toleft, and pop the front of either deque if that index is now less thanleft. - The window
[left, right]is valid. Setbest = max(best, right - left + 1). - Return
best.
Step-by-step example
nums = [8,2,4,7], limit = 4
- Index 0 (8) goes into both deques. The window [8] is valid, so
best = 1. - Index 1 (2) pops 8 from the min deque. Now max 8 - min 2 = 6 > 4, so
leftmoves to 1 and index 0 leaves the max deque. The window is [2]. - Index 2 (4) pops 2 from the max deque. Max 4 - min 2 = 2, so the window [2,4] is valid and
best = 2. - Index 3 (7) pops 4 from the max deque. Max 7 - min 2 = 5 > 4, so
leftmoves 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 best1class Solution {
2 public int longestSubarray(int[] nums, int limit) {
3 Deque<Integer> maxQ = new ArrayDeque<>();
4 Deque<Integer> minQ = new ArrayDeque<>();
5 int left = 0, best = 0;
6 for (int right = 0; right < nums.length; right++) {
7 while (!maxQ.isEmpty() && nums[maxQ.peekLast()] < nums[right]) {
8 maxQ.pollLast();
9 }
10 maxQ.offerLast(right);
11 while (!minQ.isEmpty() && nums[minQ.peekLast()] > nums[right]) {
12 minQ.pollLast();
13 }
14 minQ.offerLast(right);
15 while (nums[maxQ.peekFirst()] - nums[minQ.peekFirst()] > limit) {
16 left++;
17 if (maxQ.peekFirst() < left) {
18 maxQ.pollFirst();
19 }
20 if (minQ.peekFirst() < left) {
21 minQ.pollFirst();
22 }
23 }
24 best = Math.max(best, right - left + 1);
25 }
26 return best;
27 }
28}1class Solution {
2public:
3 int longestSubarray(vector<int>& nums, int limit) {
4 deque<int> maxQ, minQ;
5 int left = 0, best = 0;
6 for (int right = 0; right < (int)nums.size(); right++) {
7 while (!maxQ.empty() && nums[maxQ.back()] < nums[right]) {
8 maxQ.pop_back();
9 }
10 maxQ.push_back(right);
11 while (!minQ.empty() && nums[minQ.back()] > nums[right]) {
12 minQ.pop_back();
13 }
14 minQ.push_back(right);
15 while (nums[maxQ.front()] - nums[minQ.front()] > limit) {
16 left++;
17 if (maxQ.front() < left) {
18 maxQ.pop_front();
19 }
20 if (minQ.front() < left) {
21 minQ.pop_front();
22 }
23 }
24 best = max(best, right - left + 1);
25 }
26 return best;
27 }
28};Time and space complexity
O(n)
Each index is appended to each deque once and removed at most once, and left only moves forward.
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
leftpast 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
bestbefore 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.