#2302

Count Subarrays With Score Less Than K

Hard
ArrayBinary SearchSliding WindowPrefix SumSliding WindowPrefix Sum
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 combined with prefix sums to efficiently count valid subarrays. By maintaining a window of elements, we can dynamically calculate scores without recalculating sums from scratch.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize variables for the current sum, left pointer, and a counter for valid subarrays.
  2. 2Step 2: Iterate through the array with a right pointer to expand the window.
  3. 3Step 3: For each new element added, calculate the new score and check if it's less than k.
  4. 4Step 4: If the score exceeds k, increment the left pointer to shrink the window until the score is valid again.
  5. 5Step 5: For each valid configuration, add the number of valid subarrays ending at the right pointer to the counter.
solution.py13 lines
1# Full working Python code
2
3def countSubarrays(nums, k):
4    count = 0
5    current_sum = 0
6    left = 0
7    for right in range(len(nums)):
8        current_sum += nums[right]
9        while (current_sum * (right - left + 1)) >= k:
10            current_sum -= nums[left]
11            left += 1
12        count += (right - left + 1)
13    return count

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(1) since we only use a few extra variables.

  • 1Understanding how the score is calculated helps in optimizing the solution.
  • 2Using a sliding window allows us to efficiently manage the sum and length of subarrays.

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