Skip to content
Problem 1343 · LeetCode 1343(opens in a new tab)

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

MediumArrays

You get an array of positive whole numbers arr and two whole numbers, k and threshold.

Count the blocks of exactly k neighbouring numbers in arr whose average is at least threshold, and return that count. Blocks may overlap.

Example 1

Input:  arr = [3, 6, 1, 8, 4, 2], k = 2, threshold = 4
Output: 3
Why:    [3, 6], [1, 8] and [8, 4] average 4.5, 4.5 and 6
2 more examples and the constraints

Example 2

Input:  arr = [7, 1, 2], k = 3, threshold = 4
Output: 0
Why:    the only block averages 10 / 3, below 4

Example 3

Input:  arr = [5, 5, 5, 5], k = 1, threshold = 5
Output: 4
Why:    each single 5 meets the threshold exactly

Constraints

  • 1 ≤ length of arr ≤ 100,000
  • 1 ≤ arr[i] ≤ 10,000
  • 1 ≤ k ≤ length of arr
  • 0 ≤ threshold ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sum every windowO(n · k)
  2. Sliding window sumO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbers, k = 50,000Verdict
Sum every windowO(n · k)
Too slow for large k
Sliding window sumO(n)
Best; one add and one subtract per number

n = length of arr, k = window length.

Edge cases to test

  • Threshold 0. Every window passes, so the answer is n − k + 1.
  • Average not a whole number. [7, 1, 2] with k = 3 averages 3.33; with threshold 3 it passes, with threshold 4 it fails.
  • k equals the length. Only one window, the whole array.
  • Exactly on the threshold. An average equal to threshold counts.

Common mistakes

  • Dividing the sum by k in integer arithmetic, so 10 / 3 becomes 3 and passes a threshold of 3.33.
  • Counting windows before the first one has k numbers.
  • Using > instead of ≥, which drops windows that hit the threshold exactly.

How to talk through it

  1. 1Clarify. Do windows overlap? (Yes.) Does an average equal to the threshold count? (Yes.)
  2. 2Give the brute force. Sum each window from scratch: O(n · k).
  3. 3Remove the division. Average ≥ threshold is the same as sum ≥ k · threshold.
  4. 4Code the window. Add arr[i], subtract arr[i − k], test once the window is full.
  5. 5Test out loud. Run threshold 0, k = n and a window that lands exactly on the threshold.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?