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

medium sliding window fixed window array

Problem

Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k whose average is greater than or equal to threshold. Because every window has the same length, an average meets the threshold exactly when the window's sum is at least k × threshold.

Inputarr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output3
Windows [2,5,5], [5,5,5] and [5,5,8] have averages 4, 5 and 6; all other size-3 windows fall below 4.
Inputarr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
Output6
The first six size-3 windows each average more than 5.

def num_of_subarrays(arr, k, threshold):
    target = k * threshold
    window = sum(arr[:k])
    count = 1 if window >= target else 0
    for i in range(k, len(arr)):
        window += arr[i] - arr[i - k]
        if window >= target:
            count += 1
    return count
function numOfSubarrays(arr, k, threshold) {
  const target = k * threshold;
  let window = 0;
  for (let i = 0; i < k; i++) window += arr[i];
  let count = window >= target ? 1 : 0;
  for (let i = k; i < arr.length; i++) {
    window += arr[i] - arr[i - k];
    if (window >= target) count++;
  }
  return count;
}
int numOfSubarrays(int[] arr, int k, int threshold) {
    int target = k * threshold;
    int window = 0;
    for (int i = 0; i < k; i++) window += arr[i];
    int count = window >= target ? 1 : 0;
    for (int i = k; i < arr.length; i++) {
        window += arr[i] - arr[i - k];
        if (window >= target) count++;
    }
    return count;
}
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
    int target = k * threshold;
    int window = 0;
    for (int i = 0; i < k; i++) window += arr[i];
    int count = window >= target ? 1 : 0;
    for (int i = k; i < (int)arr.size(); i++) {
        window += arr[i] - arr[i - k];
        if (window >= target) count++;
    }
    return count;
}
Time: O(n) Space: O(1)