Problem 713

Abstract / Summary

Given an array of positive integers and a number k, count how many contiguous subarrays have a product less than k.

Note

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

Python 0713.py

class Solution:
    def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
        result = 0
        if k <= 1: # impossible
            return 0

        left = 0
        have = 1
        for right in range(len(nums)):
            # extend array
            have *= nums[right]
            # shrink until product is strictly less than k
            while have >= k:
                have //= nums[left]
                left  += 1

            result += right - left + 1

        return result
19 lines | 529 bytes | submitted March 30, 2024 | GitHub   21% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Prefix Sum
  • 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 Solution class implements a method that counts the number of contiguous sub-arrays whose product of elements is strictly less than a given threshold k. It processes the input list nums in a single pass, maintaining a dynamic window that expands and contracts to satisfy the product constraint. The result is accumulated as the window slides across the array.

Key Steps

Input validation

Before any processing begins, the method checks whether the threshold k is less than or equal to one. Since every element in nums is a positive integer, a product can never be less than one, making any further computation unnecessary. In that case the function returns zero immediately.

if k <= 1:  # impossible
    return 0

Sliding window initialization

Three variables are prepared: result to store the final count, left to mark the start of the current window, and have to hold the product of elements inside the window. All are initialized to values that represent an empty window.

result = 0
left = 0
have = 1

Expanding the window

The algorithm iterates over the indices of nums using right as the end pointer of the window. For each step, the element at right is multiplied into have, thereby extending the window to include the new element.

for right in range(len(nums)):
    have *= nums[right]  # extend array

Shrinking the window

If the product have reaches or exceeds k, the window is too large. A while loop repeatedly removes the leftmost element by integer division and advances left until the product falls strictly below k. This ensures the invariant that the current window always satisfies the constraint.

while have >= k:
    have //= nums[left]
    left += 1

Counting sub-arrays

After the window has been adjusted, every sub-array that ends at right and starts anywhere between left and right (inclusive) is guaranteed to have a product less than k. The number of such sub-arrays is right - left + 1, and this quantity is added to result.

result += right - left + 1

Returning the answer

When the loop finishes, result holds the total count of qualifying sub-arrays, which is then returned.

return result

Edge Cases Handled

The early return for k <= 1 addresses the scenario where no positive-integer product can satisfy the condition, eliminating unnecessary work. An empty input list is also handled gracefully: the for loop does not execute, leaving result at its initial value of zero, which is the correct count. The use of integer division (//) when shrinking the window ensures that the product remains an integer throughout, avoiding floating-point inaccuracies even when the product becomes large. Because the algorithm only removes elements from the left side after they have been multiplied in, it correctly manages cases where consecutive large numbers temporarily push the product over the threshold before smaller numbers later bring it back under control.

Performance Optimizations

The method employs a sliding-window technique that processes each element of nums at most twice-once when it is multiplied into have and possibly once when it is divided out. This eliminates the need for nested loops or repeated recomputation of products for overlapping sub-arrays. By maintaining the product incrementally, the algorithm avoids the overhead of recomputing the product from scratch for every possible sub-array. The use of integer arithmetic (* and //) keeps operations fast and memory-light, as no auxiliary data structures are allocated beyond a few scalar variables. The single-pass design ensures that the runtime scales linearly with the length of the input list, making the solution efficient for large datasets.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of building blocks, each with a different number painted on it. The goal is to find all the little groups of blocks sitting next to each other where the total you get by multiplying all their numbers together is smaller than a special number called k.

Think of this like having a magic sliding window that moves across the row of blocks. The window starts very small and grows larger as it moves to the right, adding one block at a time to a big pile. When the pile grows, the total product keeps getting bigger. If the total becomes too large, the window shifts its left side forward to take out the blocks from the beginning of the group. By removing those blocks, the total product goes down again.

Every time the window moves or shrinks, it keeps track of how many valid smaller groups exist within that current space. Because the window always keeps the numbers inside small enough, it successfully counts every possible group that works. By the time the window reaches the very end of the line of blocks, all the winning groups have been safely gathered up and counted.

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 = 9 | μ = 8.30 | σ = 0.90

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++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# JS Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
lkwq007 Python
pruthvikp Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
pruthvikp Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
46 links | 29 authors | 10 languages

Videos

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

Similar Problems

2 similar problems

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