Skip to main content

Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit - Solution & Explanation

MediumArrayQueueSliding WindowHeap (Priority Queue)39 min readAsked at: Amazon, Microsoft, Meta +12
Practice this problem

Problem Statement

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 <= 105
  • 1 <= nums[i] <= 109
  • 0 <= limit <= 109

Approach Overview

Problem 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.

Approach 1: Sliding Window with Deques

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.

  • Initialize two pointers `left` and `right` to represent the bounds of the sliding window.
  • Iterate with the `right` pointer over each element of the array.
  • Use the deques to quickly obtain the maximum and minimum values in the current window.
  • If the difference between the maximum and minimum exceeds the limit, increment the `left` pointer to attempt reducing the window size.
  • Keep track of the maximum size of the window that satisfies the condition.

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.

Code

Python

C++

Java

JavaScript

C#

Complexity

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.

Try this approach in the editor →

Approach 2: Sliding Window with TreeMap (Java)

This approach uses a sliding window implemented with a TreeMap to automatically manage and get minimum and maximum values from the current window range.

  • The TreeMap data structure provides built-in sorting and easy retrieval for both floor (minimum) and ceiling (maximum) elements.
  • By expanding the window with the right pointer, the map logs occurrences of each element within the window.
  • On conflicting with the limit constraint, the left pointer removes items from the TreeMap to reevaluate conditions.

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.

Code

Java

Complexity

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.

Try this approach in the editor →

Approach 3: Ordered Set + Sliding Window

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.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Approach 4: Binary Search + Sliding Window

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.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Approach 5: Sliding Window + Deque

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.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
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

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sliding Window with Monotonic DequesO(n)O(n)Best overall solution when you need constant-time min and max tracking inside a sliding window
Sliding Window with TreeMapO(n log n)O(n)Simpler to implement when the language provides ordered maps or sets

Video Solution

Leetcode - Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitFraz31,772 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit easy or hard?
The problem is generally rated Medium difficulty. The sliding window idea is straightforward, but efficiently maintaining both the minimum and maximum inside the window requires understanding monotonic queues, which many candidates encounter for the first time in this type of problem.
Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit Python/Java solution
Most implementations use the sliding window with monotonic deque pattern. Python uses collections.deque, Java typically uses ArrayDeque, and C++ uses deque from the STL. The algorithm maintains decreasing and increasing deques to track the current window's maximum and minimum values.
How to solve Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit in O(n)?
Use a sliding window with two deques: one decreasing deque for maximum values and one increasing deque for minimum values. Expand the right pointer while inserting elements into both structures. If the difference between the deque fronts exceeds the limit, move the left pointer and remove outdated elements. This keeps max and min queries O(1), producing an overall O(n) algorithm.
What is the best approach for Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit?
The optimal approach uses a sliding window with two monotonic deques to maintain the current maximum and minimum values. This allows checking the constraint max − min ≤ limit in constant time while expanding and shrinking the window. Each element is processed once, resulting in O(n) time complexity and O(n) space.
Is Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit asked at Google/Amazon/Meta?
Sliding window problems with min/max constraints appear frequently in interviews at companies such as Amazon, Google, and Meta. Variants of this problem test your ability to maintain dynamic window statistics using data structures like monotonic queues or ordered maps.
What data structure is used in Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit?
The most efficient solution uses two monotonic deques to track the maximum and minimum values within the sliding window. Another common implementation uses an ordered map such as TreeMap to keep elements sorted and retrieve the smallest and largest values quickly.
What is the time complexity of Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit?
The optimal monotonic deque solution runs in O(n) time because every element is added and removed from the deques at most once. Space complexity is O(n) in the worst case for the deques. An alternative TreeMap solution takes O(n log n) time due to ordered map insertions and deletions.

Ready to solve this problem?

Practice Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit with our built-in code editor and test cases.

Practice on FleetCode