SDE & MLE Prep

713. Subarray Product Less Than K

Problem

Given positive integers nums, count the contiguous subarrays whose product is strictly less than k.

Example: nums = [10,5,2,6], k = 100 → 8

Constraints: n ≤ 3·10⁴; 1 ≤ nums[i] ≤ 1000; 0 ≤ k ≤ 10⁶.

For each right end r, shrink until product < k; then every subarray ending at r and starting in [l, r] qualifies → add r − l + 1.

Complexity: O(n) time, O(1) space.

class Solution:
    def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
        if k <= 1:
            return 0
        prod, l, count = 1, 0, 0
        for r, x in enumerate(nums):
            prod *= x
            while prod >= k:
                prod //= nums[l]
                l += 1
            count += r - l + 1
        return count