#2444

Count Subarrays With Fixed Bounds

Hard
ArrayQueueSliding WindowMonotonic QueueSliding WindowTwo Pointers
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal approach uses a sliding window technique to efficiently count the valid subarrays without generating all possible subarrays. We keep track of the last positions of minK and maxK to determine valid subarrays quickly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize variables to track the last positions of minK and maxK, and a count of valid subarrays.
  2. 2Step 2: Iterate through the array, updating the last seen positions of minK and maxK.
  3. 3Step 3: For each element, calculate the number of valid subarrays that can end at the current position based on the last seen positions.
solution.py14 lines
1# Full working Python code
2
3def countSubarrays(nums, minK, maxK):
4    count = 0
5    lastMinK = lastMaxK = leftBound = -1
6    for i, num in enumerate(nums):
7        if num < minK or num > maxK:
8            leftBound = i
9        if num == minK:
10            lastMinK = i
11        if num == maxK:
12            lastMaxK = i
13        count += max(0, min(lastMinK, lastMaxK) - leftBound)
14    return count

Complexity note: This complexity is achieved because we only make a single pass through the array, updating indices and counts without needing nested loops.

  • 1The problem can be efficiently solved using the sliding window technique by tracking the last seen indices of minK and maxK.
  • 2Understanding the boundaries of valid subarrays is crucial for optimizing the solution.

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