#1438

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

Medium
ArrayQueueSliding WindowHeap (Priority Queue)Ordered SetMonotonic QueueSliding WindowTwo PointersDeque
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can use a sliding window approach to efficiently find the longest subarray. By maintaining the maximum and minimum values in the current window, we can quickly check if the absolute difference is within the limit.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize two pointers (left and right) and a variable to track the maximum length.
  2. 2Step 2: Use a data structure (like a deque) to maintain the maximum and minimum values in the current window.
  3. 3Step 3: Expand the right pointer to include more elements until the condition (max - min > limit) is violated.
  4. 4Step 4: If violated, move the left pointer to shrink the window until the condition is satisfied again.
  5. 5Step 5: Update the maximum length whenever the current window is valid.
solution.py22 lines
1from collections import deque
2
3def longestSubarray(nums, limit):
4    left = 0
5    max_length = 0
6    max_deque = deque()
7    min_deque = deque()
8    for right in range(len(nums)):
9        while max_deque and nums[max_deque[-1]] <= nums[right]:
10            max_deque.pop()
11        max_deque.append(right)
12        while min_deque and nums[min_deque[-1]] >= nums[right]:
13            min_deque.pop()
14        min_deque.append(right)
15        while nums[max_deque[0]] - nums[min_deque[0]] > limit:
16            left += 1
17            if max_deque[0] < left:
18                max_deque.popleft()
19            if min_deque[0] < left:
20                min_deque.popleft()
21        max_length = max(max_length, right - left + 1)
22    return max_length

Complexity note: The time complexity is O(n) because each element is processed at most twice (once added and once removed). The space complexity is O(n) due to the deques storing indices of the elements.

  • 1Using a sliding window allows us to efficiently manage the current subarray without recalculating max/min from scratch.
  • 2Maintaining deques for max/min values helps in quickly determining if the current window is valid.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.