This problem is a perfect example of fixed-size sliding window.If you’re new to sliding window, this problem helps you understand:
- how a window is formed
- how it slides
- how recalculation is avoided
Problem in Simple Words
You are given:
- an array arr
- a window size k
- a threshold
Your task:
Count how many contiguous subarrays of size k have an average ≥ threshold.
Key Observation
Average condition:
average ≥ threshold
Multiply both sides by k:
sum ≥ threshold × k
So instead of calculating average every time,
we just compare the window sum.
Why Sliding Window?
Brute force would:
- recalculate the sum for every subarray
Sliding window:
- calculate once
- remove the left element
- add the right element
- reuse the sum
Sliding Window Process
- Calculate the sum of the first window
- Check if it satisfies the condition
- Slide the window:
- remove arr[i - k]
- add arr[i] -> Repeat until the array ends
C++ Code
class Solution {
public:
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
int winSum = 0, count = 0;
// first window
for (int i = 0; i < k; i++)
winSum += arr[i];
if (winSum / k >= threshold)
count++;
// slide the window
for (int i = k; i < arr.size(); i++) {
winSum -= arr[i - k]; // leaving element
winSum += arr[i]; // entering element
if (winSum / k >= threshold)
count++;
}
return count;
}
};
Example Walkthrough
Example 1
arr = [2,2,2,2,5,5,5,8]
k = 3
threshold = 4
Valid subarrays:
[2,5,5]
[5,5,5]
[5,5,8]
Output: 3
Complexity
Time O(n)
Space O(1)
Efficient and clean.
What I Learned
-> window avoids recalculating sums
-> Only one element leaves and one enters
-> Fixed window problems are very structured
-> Convert average condition to sum condition
Pattern Reminder
If a problem says:
subarray
size k
sum / average / count
Try fixed sliding window first.
Final Thoughts
This problem helped me understand sliding window mechanics ,pointer movement logic ,why fixed windows are simple and powerful
If you’re learning sliding window, LeetCode 1343 is a must-solve. 🚀

Top comments (0)