LeetCode 1343 Number of Subarrays of Size K and Average Greater than Equal to Threshold

link to the problem

This is sliding window problem. Let’s see how sliding window elegantly solves the problem.

Bruteforce: generate all subarrays of size k. Then compute the average of all the subarrays that are greater than equal to the threshold.
Time complexity is O(n^2) for generating subarrays and computing the average.

Is there a better way than this?
If so, it should be better than O(n^2). What are better time complexities?
1. O(n log n) is not applicable because sorting or divide & conquer doesn’t help anything when finding subarrays
2. O(n) seems to be good candidate. But how?

Sliding Window

The problem already defined the size of the subarrays – k. It means I need to maintain window size of k and see if the average of subarray is greater than equal to threshold.

OK. so there is a progress because traversing the array with window size k is O(n) complexity.
But how are you going to compute the average? Are you going to compute the average everytime you move the window?
That would make the entire time complexity O(n^2)

Computing the average of a subarray

Note that there are a lot of duplicate average computation if it’s computed while moving the window.

Let’s look at the example array above.
Let’s say the window size is 3.
Your first window will be 1,2,3
Your second window will be 2,3,4
If you recognize, there is a double computation of adding 2, 3 for both windows.

How can you avoid the double computation?
The answer is simple: keep track of the sum of the window.
As you move the window, you subtract the element that went out of the window. And add the new element.
For example, your first window (1,2,3) sub is 6. Next window (2,3,4), you subtract 1 and add 4.

Now, you can easily compute the average (window sum / k). What do you need to do next? just check if the average is greater than threshold.

int numOfSubarrays(vector<int>& arr, int k, int threshold) {
    int sum = accumulate(begin(arr), begin(arr) + k, 0);
    int result = sum / k >= threshold ? 1 : 0;

    for (int i = k ; i < arr.size(); ++i) {
        sum -= arr[i-k];
        sum += arr[i];
        result += sum / k >= threshold ? 1 : 0;
    }

    return result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *