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

Medium

Topics
ArraySliding WindowMonotonic Queue

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

6011325394length 3
The braced window’s largest and smallest values differ by no more than the limit — length 3.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [6,1,3,5,9], limit = 4
Output: 3
Explanation: [1,3,5] has max - min = 4.

Example 2

202172232425length 3
Input:  nums = [2,2,7,2,2,2], limit = 0
Output: 3

Example 3

100201length 1
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

  1. 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 push nums[r] onto both.
  2. While maxDeque.front - minDeque.front > limit, advance l; when nums[l] leaves the window, drop it from the front of whichever deque holds it.
  3. Record r - l + 1 after 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 best
SensAI
Beta
Tap the mic to stop voice mode