DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on

Number of Subarrays of Size K With Average Threshold (LeetCode 1343)

This problem is a perfect example of fixed-size sliding window.If you’re new to sliding window, this problem helps you understand:

  1. how a window is formed
  2. how it slides
  3. how recalculation is avoided

Problem in Simple Words

You are given:

  • an array arr
  • a window size k
  • a threshold

Your task:

Count how many contiguous subarrays of size k have an average ≥ threshold.

Key Observation

Average condition:

average ≥ threshold

Enter fullscreen mode Exit fullscreen mode

Multiply both sides by k:

sum ≥ threshold × k
Enter fullscreen mode Exit fullscreen mode

So instead of calculating average every time,
we just compare the window sum.

Why Sliding Window?

Brute force would:

  • recalculate the sum for every subarray

Sliding window:

  • calculate once
  • remove the left element
  • add the right element
  • reuse the sum

Sliding Window Process

  1. Calculate the sum of the first window
  2. Check if it satisfies the condition
  3. Slide the window:
    • remove arr[i - k]
    • add arr[i] -> Repeat until the array ends

C++ Code

class Solution {
public:
    int numOfSubarrays(vector<int>& arr, int k, int threshold) {
        int winSum = 0, count = 0;

        // first window
        for (int i = 0; i < k; i++)
            winSum += arr[i];

        if (winSum / k >= threshold)
            count++;

        // slide the window
        for (int i = k; i < arr.size(); i++) {
            winSum -= arr[i - k]; // leaving element
            winSum += arr[i];     // entering element

            if (winSum / k >= threshold)
                count++;
        }

        return count;
    }
};
Enter fullscreen mode Exit fullscreen mode

Example Walkthrough

Example 1

arr = [2,2,2,2,5,5,5,8]
k = 3
threshold = 4
Enter fullscreen mode Exit fullscreen mode

Valid subarrays:

[2,5,5]

[5,5,5]

[5,5,8]
Enter fullscreen mode Exit fullscreen mode

Output: 3

Complexity

Time    O(n)
Space   O(1)
Enter fullscreen mode Exit fullscreen mode

Efficient and clean.

What I Learned

-> window avoids recalculating sums
-> Only one element leaves and one enters
-> Fixed window problems are very structured
-> Convert average condition to sum condition

Pattern Reminder

If a problem says:

subarray
size k
sum / average / count
Try fixed sliding window first.

Final Thoughts

This problem helped me understand sliding window mechanics ,pointer movement logic ,why fixed windows are simple and powerful

If you’re learning sliding window, LeetCode 1343 is a must-solve. 🚀

Top comments (0)