Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold - Problem
Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold.
A sub-array is a contiguous sequence of elements within an array. The average of a sub-array is the sum of all elements divided by the number of elements.
Note: The average should be calculated as a floating-point number, but the comparison with threshold should handle integer arithmetic to avoid precision issues.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [2,4,2,1,5], k = 3, threshold = 2
›
Output:
2
💡 Note:
Sub-array [2,4,2] has average (2+4+2)/3 = 2.67 ≥ 2. Sub-array [4,2,1] has average (4+2+1)/3 = 2.33 ≥ 2. Sub-array [2,1,5] has average (2+1+5)/3 = 2.67 ≥ 2. However, only first two qualify, so answer is 2.
Example 2 — All Valid
$
Input:
arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
›
Output:
6
💡 Note:
Most sub-arrays of size 3 have averages well above 5, so multiple sub-arrays qualify.
Example 3 — None Valid
$
Input:
arr = [1,1,1,1,1], k = 1, threshold = 2
›
Output:
0
💡 Note:
All elements are 1, which is less than threshold 2, so no sub-arrays qualify.
Constraints
- 1 ≤ arr.length ≤ 105
- 1 ≤ arr[i] ≤ 104
- 1 ≤ k ≤ arr.length
- 0 ≤ threshold ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [2,4,2,1,5], k=3, threshold=2
2
Process
Check each sub-array of size 3 for average ≥ 2
3
Output
Count of valid sub-arrays = 2
Key Takeaway
🎯 Key Insight: Use sliding window to avoid recalculating sums - just add new element and remove old element
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code