sagelearnai

Subarray Product Less Than K

Difficulty: Medium · Pattern: Sliding Window · LeetCode #713

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

Examples

text
nums = [10, 5, 2, 6], k = 100  →  8
nums = [1, 2, 3], k = 0        →  0

Hints

  1. Keep the largest window ending at r whose product is below k.
  2. Every subarray ending at r and starting at or after l qualifies: that's r − l + 1 subarrays.

Approach

Expand r, multiplying prod by nums[r]; while prod ≥ k, divide by nums[l] and move l forward. All subarrays [l..r], [l+1..r], …, [r..r] then have a product below k, so add r − l + 1. If k ≤ 1, no product of positive integers is below it, so return 0.

Complexity

Time: O(n). Space: O(1).

Python solution
def numSubarrayProductLessThanK(nums, k):
    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
JavaScript solution
function numSubarrayProductLessThanK(nums, k) {
  if (k <= 1) return 0;
  let prod = 1, l = 0, count = 0;
  for (let r = 0; r < nums.length; r++) {
    prod *= nums[r];
    while (prod >= k) prod /= nums[l++];
    count += r - l + 1;
  }
  return count;
}