#2762
Continuous Subarrays
MediumArrayQueueSliding WindowHeap (Priority Queue)Ordered SetMonotonic QueueSliding WindowTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using the sliding window technique allows us to efficiently find continuous subarrays by maintaining a range of valid elements. This reduces the need for nested loops and checks.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers (left and right) and a count variable.
- 2Step 2: Expand the right pointer to include elements in the window while maintaining the condition that the difference between max and min is <= 2.
- 3Step 3: If the condition fails, move the left pointer to shrink the window until the condition is satisfied again.
- 4Step 4: For each position of the right pointer, the number of valid subarrays ending at right is (right - left + 1).
solution.py9 lines
1def countContinuousSubarrays(nums):
2 left = 0
3 count = 0
4 n = len(nums)
5 for right in range(n):
6 while max(nums[left:right+1]) - min(nums[left:right+1]) > 2:
7 left += 1
8 count += (right - left + 1)
9 return countℹ
Complexity note: The optimal solution runs in O(n) because each element is processed at most twice (once when added and once when removed), making it linear with respect to the input size.
- 1The problem can be efficiently solved using the sliding window technique, which allows us to dynamically adjust the range of valid subarrays.
- 2Understanding the relationship between the maximum and minimum values in a subarray is crucial to solving this problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.