Problem 1343

Abstract / Summary

Count how many groups of k consecutive numbers have an average at least as large as the given threshold.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1343.py

class Solution:
    def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
        result = 0

        need = threshold * k
        have = sum(arr[:k - 1])
        for i in range(k - 1, len(arr)):
            have += arr[i]
            if have >= need:
                result += 1
            have -= arr[i - k + 1]

        return result
13 lines | 370 bytes | submitted January 9, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method numOfSubarrays that counts how many contiguous subarrays of length k have an average value greater than or equal to a given threshold. The method receives an integer list arr, the subarray length k, and the threshold. By converting the average condition into a sum comparison, the algorithm avoids floating-point arithmetic and works directly with integer values.

Key Steps

The method begins by initializing a counter result to zero. This variable accumulates the number of qualifying subarrays.

result = 0

Next, the required total sum for a subarray to meet the threshold is pre-computed. Multiplying threshold by k yields the minimum sum (need) that any length-k window must reach.

need = threshold * k

The algorithm then prepares a running sum have that represents the sum of the current sliding window. It starts by summing the first k-1 elements of the array. This partial sum sets up the window before the main iteration begins.

have = sum(arr[:k - 1])

The core of the solution is a single loop that iterates from index k-1 to the end of the array. In each iteration the element at the current index i is added to have, completing the window of size k. The sum is then compared against need. If the condition holds, result is incremented. After the check, the element that falls out of the window (at position i-k+1) is subtracted from have, preparing the sum for the next slide.

for i in range(k - 1, len(arr)):
    have += arr[i]
    if have >= need:
        result += 1
    have -= arr[i - k + 1]

Finally, the method returns the accumulated count.

return result

Edge Cases

The code gracefully handles the situation where the input array is shorter than the required window length k. In that case, the range in the for loop becomes empty because range(k - 1, len(arr)) yields no indices, and the method returns zero without entering the loop. This implicitly covers the edge case of insufficient elements.

When k equals one, the initial sum have is computed over an empty slice (arr[:0]), resulting in zero. The loop then processes each element individually, adding it to have, performing the comparison, and immediately subtracting the same element. This effectively checks each single element against the threshold, correctly counting qualifying elements.

If threshold is negative or zero, the multiplication threshold * k still yields a valid integer need. The comparison have >= need works without special handling, allowing the function to count subarrays whose average meets or exceeds a non-positive threshold.

Performance Optimizations

The algorithm employs a sliding window technique that maintains a running sum instead of recomputing the sum of each subarray from scratch. By adding the new element and removing the element that exits the window in constant time, the method achieves linear traversal of the input list. This eliminates the overhead of nested loops and reduces the total number of arithmetic operations.

Pre-computing the target sum (need) removes the need for division inside the loop, avoiding floating-point operations and potential rounding errors. Working exclusively with integers also improves cache friendliness and speeds up the comparison step.

The initial partial sum (have = sum(arr[:k - 1])) leverages Python’s built-in sum function, which is implemented in C and therefore faster than a manual Python loop for the same purpose. This small upfront cost is offset by the overall linear complexity of the sliding window traversal.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of numbered toy blocks. This code is like a little robot helper that looks at a tiny group of these blocks at a time to see if they are heavy enough to win a prize.

First, the robot figures out the magic score it is looking for by multiplying the threshold number by the size of the group. It adds up the values of the first few blocks to get a head start. Then, it walks down the row of blocks one by one. Each time it steps forward, it picks up the new block in front and adds its value to the total. If the total is high enough to match or beat the magic score, it keeps a tally mark on a chalkboard. After checking that group, it carefully sets aside the oldest block at the back so the group stays the same size as it moves to the next spot. This keeps happening until the robot has checked every possible group in the row.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.96 | σ = 1.00

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
keineahnung2345 C++
lzl124631x C++
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lzl124631x C++
suxrobGM C#
varunu28 Java
26 links | 15 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

2 easy 2 medium
5 solutions   January 9, 2024

Fun Facts

Longest title with 77 characters.

1 fun fact

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality