Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
Medium
Topics
Given an integer array nums and a non-negative integer limit, find the longest contiguous, non-empty stretch of nums in which the gap between the largest and the smallest element is at most limit. Return its length.
Equivalently, every pair of elements inside the stretch differs by at most limit.
Example 1
Input: nums = [6,1,3,5,9], limit = 4 Output: 3 Explanation: [1,3,5] has max - min = 4.
Example 2
Input: nums = [2,2,7,2,2,2], limit = 0 Output: 3
Example 3
Input: nums = [10,20], limit = 5 Output: 1
Constraints
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^9
- 0 <= limit <= 10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
If a window is valid, every smaller window inside it is valid too, so a sliding window works: grow the right edge, and shrink from the left only while the window breaks the rule.
The window needs its current maximum and minimum at every step. Two monotonic deques give both in O(1): one keeps candidates for the maximum in decreasing order, the other candidates for the minimum in increasing order.
Approach
- For each right index
r, pop smaller values off the back of the max-deque and larger values off the back of the min-deque, then pushnums[r]onto both. - While
maxDeque.front - minDeque.front > limit, advancel; whennums[l]leaves the window, drop it from the front of whichever deque holds it. - Record
r - l + 1after each step and return the best.
Dry Run
nums = [6, 1, 3, 5, 9], limit = 4
Two monotonic deques hold INDICES: maxq decreasing by value, minq increasing. The
window's spread is always nums[maxq[0]] - nums[minq[0]], readable in O(1).
r=0 v=6 maxq [6] minq [6] spread 0 left 0 len 1 best 1
r=1 v=1 maxq [1] minq [1] spread 0 left 1 len 1 best 1
6 then 1 is a spread of 5 > 4, so left advanced and both deques dropped the 6
r=2 v=3 maxq [3] minq [1, 3] spread 2 left 1 len 2 best 2
r=3 v=5 maxq [5] minq [1, 3, 5] spread 4 left 1 len 3 best 3
r=4 v=9 maxq [9] minq [5, 9] spread 4 left 3 len 2 best 3
answer 3 -- the run 1 3 5
Each deque drops everything it dominates on push: a new value that is larger than
the tail of maxq makes those tails permanently irrelevant, since they are both
older and smaller. So each index is pushed once and popped once -- O(n) despite
three nested-looking loops.
Storing indices rather than values is what makes the left-eviction correct. The
check is `maxq[0] == left`, identity of position, not of value. Store values
instead and a repeated number cannot be told apart from a different occurrence of
itself: on [5,4,0,4,0,6,3,2] with limit 4 the answer is 4 and the value-based
version reports 5. They disagree on 2126 of 20000 random inputs.
Given indices, popping on <= and >= -- which discards duplicates -- is then
safe, and so is popping on strict < and >, which keeps them. The page's code
takes the first option.Complexity
- Time — O(n): each element enters and leaves each deque once.
- Space — O(n): the deques in the worst case.
Common Pitfalls
- Store indices in the deques, not values. The left-eviction test is
maxq[0] == left, an identity of position: with values stored, one occurrence of a repeated number cannot be distinguished from another, and on[5,4,0,4,0,6,3,2]with limit 4 the answer is 4 while the value-based version reports 5 — they disagree on 2126 of 20000 random inputs. Given indices, popping on<=and>=is then safe, and so is popping on strict<and>. - A sorted multiset (TreeMap) also works in O(n log n) and is a fine fallback in an interview.
Full Solution — all languages
class Solution:
def longestSubarray(self, nums, limit):
from collections import deque
maxq, minq = deque(), deque()
left = 0
best = 0
for right, v in enumerate(nums):
while maxq and nums[maxq[-1]] <= v:
maxq.pop()
maxq.append(right)
while minq and nums[minq[-1]] >= v:
minq.pop()
minq.append(right)
while nums[maxq[0]] - nums[minq[0]] > limit:
if maxq[0] == left:
maxq.popleft()
if minq[0] == left:
minq.popleft()
left += 1
best = max(best, right - left + 1)
return bestimport java.util.*;
class Solution {
public int longestSubarray(int[] nums, int limit) {
Deque<Integer> maxq = new ArrayDeque<>(), minq = new ArrayDeque<>();
int left = 0, best = 0;
for (int right = 0; right < nums.length; right++) {
while (!maxq.isEmpty() && nums[maxq.peekLast()] <= nums[right]) maxq.pollLast();
maxq.addLast(right);
while (!minq.isEmpty() && nums[minq.peekLast()] >= nums[right]) minq.pollLast();
minq.addLast(right);
while (nums[maxq.peekFirst()] - nums[minq.peekFirst()] > limit) {
if (maxq.peekFirst() == left) maxq.pollFirst();
if (minq.peekFirst() == left) minq.pollFirst();
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int longestSubarray(vector<int>& nums, int limit) {
deque<int> maxq, minq;
int left = 0, best = 0;
for (int right = 0; right < (int)nums.size(); right++) {
while (!maxq.empty() && nums[maxq.back()] <= nums[right]) maxq.pop_back();
maxq.push_back(right);
while (!minq.empty() && nums[minq.back()] >= nums[right]) minq.pop_back();
minq.push_back(right);
while (nums[maxq.front()] - nums[minq.front()] > limit) {
if (maxq.front() == left) maxq.pop_front();
if (minq.front() == left) minq.pop_front();
left++;
}
best = max(best, right - left + 1);
}
return best;
}
};/**
* @param {number[]} nums
* @param {number} limit
* @return {number}
*/ var longestSubarray = function(nums, limit) {
const maxq = [], minq = [];
let left = 0, best = 0, mh = 0, mt = 0, nh = 0, nt = 0;
for (let right = 0; right < nums.length; right++) {
while (mt > mh && nums[maxq[mt - 1]] <= nums[right]) mt--;
maxq[mt++] = right;
while (nt > nh && nums[minq[nt - 1]] >= nums[right]) nt--;
minq[nt++] = right;
while (nums[maxq[mh]] - nums[minq[nh]] > limit) {
if (maxq[mh] === left) mh++;
if (minq[nh] === left) nh++;
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
};