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

Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.

A subarray is a contiguous part of an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [8,2,4,7], limit = 4
Output: 2
💡 Note: The longest subarray is [2,4] with absolute difference |4-2| = 2 ≤ 4. Length is 2.
Example 2 — Larger Limit
$ Input: nums = [10,1,2,4,7,2], limit = 5
Output: 4
💡 Note: The longest subarray is [2,4,7,2] with max difference |7-2| = 5 ≤ 5. Length is 4.
Example 3 — Single Element
$ Input: nums = [4,2,2,2,4,4,2,2], limit = 0
Output: 3
💡 Note: The longest subarray with all equal elements is [2,2,2]. Length is 3.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ limit ≤ 109
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Find Longest Subarray: max - min ≤ limitInput: [8,2,4,7], limit = 482470123[8]: diff = 0 ≤ 4 ✓[2,4]: diff = 2 ≤ 4 ✓[8,2]: diff = 6 > 4 ✗[2,4,7]: diff = 5 > 4 ✗Check all possible subarraysAnswer: 2 (length of [2,4])
Understanding the Visualization
1
Input
Array [8,2,4,7] with limit = 4
2
Process
Find longest subarray where max - min ≤ 4
3
Output
Return length of longest valid subarray
Key Takeaway
🎯 Key Insight: Use sliding window with monotonic deques to efficiently track min/max values
Asked in
Google 15 Amazon 12 Microsoft 8
32.0K Views
Medium Frequency
~25 min Avg. Time
890 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