Python coding

Count runs with a product below k

Given a list nums of positive integers and an integer k, count the contiguous, non-empty subarrays whose product is strictly less than k. Subarrays at different positions count separately: for [10, 5, 2, 6] and k = 100 the answer is 8 ([10], [5], [2], [6], [10, 5], [5, 2], [2, 6] and [5, 2, 6]).

nums may be empty; every value is ≥ 1 and 0 <= k <= 10^6. Aim for O(n): multiplying out every subarray is O(n²).

Besides the tests, one large input (6,000 values) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • count_low_product([10,5,2,6], 100) → 8
  • count_low_product([1,2,3], 0) → 0
  • count_low_product([1,1,1], 2) → 6
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Every value is at least 1, so widening a subarray never lowers its product. That monotonic rule is what a variable sliding window needs.

Hint 2

Multiply in nums[right]; while the product reaches k, divide out nums[left] and move left. Then every start from left to right works: add right - left + 1.

Hint 3

With k <= 1 no product is below k, since all are at least 1. Return 0 first, or the shrink loop runs past right.

Solution and why it works
pythonO(n) · O(1)
def count_low_product(nums: list[int], k: int) -> int:
    if k <= 1:
        return 0                         # every product is at least 1
    count = left = 0
    product = 1
    for right, x in enumerate(nums):
        product *= x
        while product >= k:
            product //= nums[left]       # exact: nums[left] is one of its factors
            left += 1
        count += right - left + 1        # the valid subarrays that end at right
    return count

Positive values make the rule monotonic: once a window's product reaches k, every wider window does too, so left only moves forward and each index enters and leaves once: O(n). Counting is the key move: if [left, right] is valid, so is every shorter window ending at right, which adds right - left + 1 at once. The trap is k <= 1: no product is below it, and without the early return the shrink loop runs past right.

Related lab: Sliding window, step by step