#1343
Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
MediumArraySliding WindowSliding WindowArray
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)
The optimal approach uses a sliding window technique to maintain the sum of the current sub-array of size k. This allows us to efficiently update the sum as we move the window, reducing the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to hold the sum of the first k elements.
- 2Step 2: Loop through the array starting from index k, updating the sum by subtracting the element going out of the window and adding the new element coming into the window.
- 3Step 3: For each updated sum, check if the average (sum / k) is greater than or equal to the threshold and increment the count accordingly.
solution.py12 lines
1# Full working Python code
2
3def numOfSubarrays(arr, k, threshold):
4 count = 0
5 current_sum = sum(arr[:k])
6 if current_sum / k >= threshold:
7 count += 1
8 for i in range(k, len(arr)):
9 current_sum += arr[i] - arr[i - k]
10 if current_sum / k >= threshold:
11 count += 1
12 return countℹ
Complexity note: This complexity is achieved because we only traverse the array once, maintaining a running sum without needing nested loops.
- 1Using a sliding window allows us to efficiently calculate the sum without recalculating it from scratch.
- 2Understanding the average condition helps in optimizing the checks needed for counting valid sub-arrays.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.