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

Imagine you're a quality control manager at a manufacturing plant. You need to find the longest continuous sequence of product measurements where the difference between the highest and lowest values doesn't exceed your quality tolerance limit.

Given an array of integers nums representing measurements and an integer limit representing your tolerance threshold, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is at most limit.

In other words, for a valid subarray, max(subarray) - min(subarray) ≤ limit.

Example: If nums = [8,2,4,7] and limit = 4, the longest valid subarray is [2,4] with length 2, because |4-2| = 2 ≤ 4.

Input & Output

example_1.py — Basic case
$ Input: nums = [8,2,4,7], limit = 4
› Output: 2
šŸ’” Note: The longest valid subarray is [2,4] with length 2, since |4-2| = 2 ≤ 4. Other valid subarrays include [8], [2], [4], [7], but they are shorter.
example_2.py — Larger limit
$ Input: nums = [10,1,2,4,7,2], limit = 5
› Output: 4
šŸ’” Note: The longest valid subarray is [2,4,7,2] with length 4, since max-min = 7-2 = 5 ≤ 5.
example_3.py — Large limit
$ Input: nums = [4,2,2,2,4,4,2,2], limit = 0
› Output: 3
šŸ’” Note: With limit = 0, all elements in a valid subarray must be equal. The longest such subarray is [2,2,2] with length 3.

Visualization

Tap to expand
8247Quality WindowQuality Control SystemMax: 4, Min: 2Variance: 4-2 = 2 ≤ 4 āœ“āœ“Approved SectionLength: 2
Understanding the Visualization
1
Initialize inspection window
Start with an empty quality control window and two tracking systems for max/min values
2
Expand window and track extremes
As products enter the window, efficiently update max/min using monotonic deques
3
Shrink when quality drops
When variance exceeds limit, remove products from left until quality is restored
4
Record best section
Track the longest section that maintained quality standards throughout
Key Takeaway
šŸŽÆ Key Insight: Monotonic deques allow O(1) max/min tracking in sliding windows, making this O(n) instead of O(n²)

Time & Space Complexity

Time Complexity
ā±ļø
O(n²)

Two nested loops - outer loop for starting position, inner loop to extend subarray

n
2n
⚠ Quadratic Growth
Space Complexity
O(1)

Only using variables to track max, min, and result length

n
2n
āœ“ Linear Space

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 0 ≤ limit ≤ 109
  • Follow up: Can you solve this in O(n) time?
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
32.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
šŸ’” Explanation
AI Ready
šŸ’” Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen