Introduction
LeetCode 1343: Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold is another excellent problem to practice the sliding window technique.
The goal is not just to compute values but to count how many subarrays satisfy a given condition efficiently.
You are given:
- An integer array
arr - An integer
krepresenting subarray size - A
thresholdvalue
You must return the number of subarrays of size k whose average is greater than or equal to the threshold.
If you'd like to try solving the problem first, you can attempt it here:
👉 Try the problem on LeetCode:
Problem Understanding
A direct approach would calculate the average for every subarray of size k. However, recomputing sums repeatedly leads to unnecessary work.
To optimize, we use a sliding window, allowing us to reuse previous computations and move efficiently across the array.
Key Idea: Sliding Window Optimization
Instead of calculating sums repeatedly:
- Maintain the sum of the current window.
- Slide the window by:
- Adding the next element
- Removing the element leaving the window
- Check if the average satisfies the threshold.
- Count valid windows.
This ensures each element is processed only once.
Approach
- Maintain two pointers to represent the window.
- Add elements until window size reaches
k. - Check if average meets the threshold.
- Move the window forward.
- Count valid subarrays.
An important optimization: instead of computing average each time, we can compare the sum with threshold * k. However, your current implementation using division also works correctly.
Implementation (Java)
Dry Run Example
Input:
Valid subarrays:
Total valid subarrays = 3
Complexity Analysis
Time Complexity: O(n)
Each element enters and leaves the window once.
Space Complexity: O(1)
Only constant extra variables are used.
Edge Cases Considered
- Threshold equals zero
- Minimum array length
- Large array sizes
- Non-integer averages
- All elements smaller than threshold
Sliding Window Pattern Importance
This problem reinforces the sliding window pattern, which appears frequently in:
- Fixed-size window problems
- Maximum or minimum subarray problems
- Counting valid segments
- String window problems
Mastering this pattern helps solve many interview questions efficiently.
Conclusion
This problem is a strong example of turning a potentially expensive brute-force approach into an efficient linear solution using sliding window.
Once you recognize this pattern, many array and string problems become significantly easier to solve.




