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.
Example 1:
Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2.
Example 2:
Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.
Example 3:
Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1090 <= limit <= 109Problem Overview: Given an integer array nums and a limit, find the length of the longest contiguous subarray where the absolute difference between the maximum and minimum elements is less than or equal to the limit.
Approach 1: Sliding Window with Monotonic Deques (O(n) time, O(n) space)
This approach maintains a dynamic window using two pointers. The key challenge is tracking the current window's minimum and maximum efficiently. Two monotonic deques solve this: one decreasing deque stores potential maximum values and one increasing deque stores potential minimum values. As you expand the right pointer, insert the new element while maintaining monotonic order. If max - min exceeds the limit, move the left pointer and remove elements leaving the window from the front of the deques.
Each element enters and leaves the deques at most once, so the total work is linear. This pattern appears frequently in sliding window problems that require maintaining window extrema efficiently. The deques act as a monotonic queue, allowing constant-time access to the current max and min.
Approach 2: Sliding Window with TreeMap (O(n log n) time, O(n) space)
This version uses a balanced ordered map such as Java's TreeMap. The sliding window expands by inserting each number into the map and tracking its frequency. The smallest and largest keys represent the current window's minimum and maximum. If the difference exceeds the limit, move the left pointer and decrement the frequency of the outgoing value, removing it when the count reaches zero.
Each insertion and deletion costs O(log n) due to tree balancing. The advantage is conceptual simplicity since the ordered map automatically keeps elements sorted. This approach is useful when a language provides efficient ordered set or map implementations but monotonic deque patterns feel less familiar.
Recommended for interviews: The monotonic deque sliding window is the expected optimal solution with O(n) time. It demonstrates mastery of window invariants and specialized queue structures. The TreeMap approach still shows solid understanding but is usually considered a step below the optimal linear solution.
This approach uses the sliding window technique along with two deques to efficiently keep track of the maximum and minimum values in the current window.
We maintain two deques - one for the indices of the maximum values and another for the minimum values, within the current window of the array, called `nums`. By utilizing the sliding window, we can dynamically adjust the start and end of the window based on whether the condition of the absolute difference being less than or equal to the limit is satisfied.
The python implementation uses two deques, `min_deque` and `max_deque`, to maintain the indices of the current window's minimum and maximum elements.
As we iterate with the `right` pointer across each element, we adjust the deques to hold only the valid elements within the current window range. If at any point the difference between the max and min exceeds the specified limit, the `left` pointer is incremented to reduce the window size.
Python
C++
Java
JavaScript
C#
Time Complexity: O(n), where n is the length of the array, because each element is added and removed from the deque at most once.
Space Complexity: O(n), due to the size of the deques which in the worst case can hold all elements.
This approach uses a sliding window implemented with a TreeMap to automatically manage and get minimum and maximum values from the current window range.
By leveraging the automatic ordering of keys within a TreeMap, this approach ensures the retrieval and conditional check of both minimum and maximum values within a determined window is efficient.
Upon the boundary violation concerning the permissible limit, the left pointer incrementally adjusts, pruning the TreeMap until the condition is restored.
Java
Time Complexity: O(n log n); each insertion and deletion operation on TreeMap takes log n time.
Space Complexity: O(n); due to the additional space required by the TreeMap.
We can enumerate each position as the right endpoint of the subarray, and find the leftmost left endpoint corresponding to it, such that the difference between the maximum and minimum values in the interval does not exceed limit. During the process, we use an ordered set to maintain the maximum and minimum values within the window.
The time complexity is O(n log n), and the space complexity is O(n). Here, n is the length of the array nums.
Python
Java
C++
Go
TypeScript
We notice that if a subarray of length k satisfies the condition, then a subarray of length k' < k also satisfies the condition. This shows a monotonicity, therefore, we can use binary search to find the longest subarray that satisfies the condition.
We define the left boundary of the binary search as l = 0, and the right boundary as r = n. For each mid = \frac{l + r + 1}{2}, we check whether there exists a subarray of length mid that satisfies the condition. If it exists, we update l = mid, otherwise we update r = mid - 1. The problem is transformed into whether there exists a subarray of length mid in the array that satisfies the condition, which is actually to find the difference between the maximum and minimum values in the sliding window does not exceed limit. We can use two monotonic queues to maintain the maximum and minimum values in the window respectively.
The time complexity is O(n times log n), and the space complexity is O(n). Where n is the length of the array nums.
Python
Java
C++
Go
TypeScript
We can use a deque to maintain the maximum and minimum values within the window. We maintain two deques, one for storing the indices of the maximum values and the other for the minimum values within the window. Define two pointers l and r to point to the left and right boundaries of the window, respectively.
Each time we move the right boundary r to the right, we check if the element corresponding to the tail index of the maximum value deque is less than the current element. If it is, we dequeue the tail element until the element corresponding to the tail of the maximum value deque is not less than the current element. Similarly, we check if the element corresponding to the tail index of the minimum value deque is greater than the current element. If it is, we dequeue the tail element until the element corresponding to the tail of the minimum value deque is not greater than the current element. Then, we enqueue the current element's index.
If the difference between the elements at the front of the maximum value deque and the minimum value deque is greater than limit, then we move the left boundary l to the right. If the element at the front of the maximum value deque is less than l, we dequeue the front element of the maximum value deque. Similarly, if the element at the front of the minimum value deque is less than l, we dequeue the front element of the minimum value deque.
The answer is n - l.
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array nums.
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Sliding Window with Deques | Time Complexity: O(n), where n is the length of the array, because each element is added and removed from the deque at most once. Space Complexity: O(n), due to the size of the deques which in the worst case can hold all elements. |
| Sliding Window with TreeMap (Java) | Time Complexity: O(n log n); each insertion and deletion operation on TreeMap takes log n time. Space Complexity: O(n); due to the additional space required by the TreeMap. |
| Ordered Set + Sliding Window | — |
| Binary Search + Sliding Window | — |
| Sliding Window + Deque | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sliding Window with Monotonic Deques | O(n) | O(n) | Best overall solution when you need constant-time min and max tracking inside a sliding window |
| Sliding Window with TreeMap | O(n log n) | O(n) | Simpler to implement when the language provides ordered maps or sets |
Leetcode - Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit • Fraz • 31,560 views views
Watch 9 more video solutions →Practice Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor