Longest Continuous Subarray With Absolute Diff ≤ Limit
Problem Statement
You are given an integer array nums and a number limit.
Find the longest contiguous subarray in which every pair of elements differs by at most limit. In other words, the absolute difference between any two elements of the subarray must be ≤ limit.
Return the length of that subarray.
An integer array nums of length n, and an integer limit.
A single number: the length of the longest subarray where any two elements differ by at most limit.
[2, 4] (difference 2) and [4, 7] (difference 3) work. Any subarray of length 3 has a pair that differs by more than 4, e.g. [2, 4, 7] has 7 − 2 = 5.
[2, 4, 7, 2] has largest 7 and smallest 2, so the biggest difference is 5, which is allowed.
With limit 0, all elements must be equal. The longest run of equal values is [2, 2, 2].
- • 1 ≤ n ≤ 10^5
- • 1 ≤ nums[i] ≤ 10^9
- • 0 ≤ limit ≤ 10^9
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each start, extend the end while tracking max and min; stop when the spread is too big
Variable window; a sorted multiset gives the window's min and max
Decreasing deque for the max, increasing deque for the min, shrink while max − min > limit
Fix a start. Move the end to the right one step at a time, keeping a running max and min. While max − min ≤ limit, the subarray is good — update the answer. As soon as it breaks, stop: a longer subarray from this start can only be worse.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.