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 → 0Hints
- Keep the largest window ending at
rwhose product is belowk. - Every subarray ending at
rand starting at or afterlqualifies: that'sr − l + 1subarrays.
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 countJavaScript 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;
}