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
Longest Subarray with Absolute Diff <= Limit INPUT nums array: 8 i=0 2 i=1 4 i=2 7 i=3 limit = 4 Find longest subarray where: |max - min| <= 4 Example: [8,2] |8-2| = 6 > 4 (invalid) Example: [2,4] |4-2| = 2 <= 4 (valid) ALGORITHM STEPS 1 Sliding Window Use two pointers (left, right) 2 Track Min/Max Use two deques (monotonic) 3 Expand Right Add element, update deques 4 Shrink if Invalid Move left when diff > limit Window Iterations: [8] max=8,min=8 diff=0 OK [8,2] max=8,min=2 diff=6 FAIL [2] shrink left [2,4] max=4,min=2 diff=2 OK [2,4,7] diff=5 FAIL --> [4,7] FINAL RESULT Longest Valid Subarray: 2 4 OR 4 7 Output: 2 OK - Length = 2 Both [2,4] and [4,7] satisfy |max-min| <= 4 Key Insight: Use a sliding window with two monotonic deques: one decreasing (for max) and one increasing (for min). This allows O(1) access to current window's max and min values. When |max - min| exceeds limit, shrink window from left until valid. Time: O(n), Space: O(n). Each element enters/exits deque once. TutorialsPoint - Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit | Optimal Solution
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