Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold - Problem

You're given an array of integers arr and two important parameters: k (the subarray size) and threshold (the minimum average). Your task is to find how many contiguous subarrays of exactly size k have an average that meets or exceeds the threshold.

Think of it as a quality control problem: you're scanning through data windows of fixed size and counting how many meet your quality standards. For example, if you have test scores [2, 2, 2, 2, 5, 5, 5, 8] and want to find 3-student groups with an average of at least 4, you'd slide a window of size 3 across the array and check each group's average.

Key insight: Instead of calculating averages (which involves division), you can multiply the threshold by k and compare against the sum directly. This avoids floating-point precision issues!

Input & Output

basic_case.py β€” Python
$ Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
β€Ί Output: 3
πŸ’‘ Note: Sub-arrays [2,5,5], [5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4.
no_valid_subarrays.py β€” Python
$ Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
β€Ί Output: 6
πŸ’‘ Note: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.
edge_case_exact_size.py β€” Python
$ Input: arr = [1,1,1], k = 3, threshold = 1
β€Ί Output: 1
πŸ’‘ Note: The only sub-array of size 3 is [1,1,1] with average 1, which equals the threshold.

Visualization

Tap to expand
222255Window: k=3Current Sum: 6Target: 4 Γ— 3 = 126 < 12 ❌Sliding Window TechniqueNext: Remove leftmost (2), Add next element (2)New Sum: 6 - 2 + 2 = 6-+
Understanding the Visualization
1
Initialize Window
Calculate sum of first k elements: [2,2,2] = 6
2
Slide Right
Remove 2, add 2: sum becomes 6-2+2 = 6
3
Continue Sliding
Remove 2, add 5: sum becomes 6-2+5 = 9
4
Check Threshold
Compare sum β‰₯ thresholdΓ—k to count valid subarrays
Key Takeaway
🎯 Key Insight: The sliding window technique eliminates redundant calculations by maintaining a running sum as we slide through the array, achieving optimal O(n) time complexity.

Time & Space Complexity

Time Complexity
⏱️
O(n*k)

For each of (n-k+1) starting positions, we sum k elements

n
2n
βœ“ Linear Growth
Space Complexity
O(1)

Only using variables to store current sum and counter

n
2n
βœ“ Linear Space

Constraints

  • 1 ≀ arr.length ≀ 105
  • 1 ≀ arr[i] ≀ 104
  • 1 ≀ k ≀ arr.length
  • 0 ≀ threshold ≀ 104
  • All array elements are positive integers
Asked in
Amazon 45 Google 32 Microsoft 28 Meta 19
42.3K Views
High Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen