Description: Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.
Code:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 1:
return 0
left = ans = 0
curr = 1
for right in range(len(nums)):
curr *= nums[right]
while curr >= k:
curr //= nums[left]
left += 1
ans += right - left + 1
return ans
Efficiency:
Time Complexity: O(n)
Space Complexity: O(1)
Test:
assert numSubarrayProductLessThanK(nums = [10,5,2,6], k = 100) == 8
assert numSubarrayProductLessThanK(nums = [1,2,3], k = 0) == 0
print("All numSubarrayProductLessThanK cases passed")
Note The 8 subarrays that have product less than 100 are:
- [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
- [10, 5, 2] is not included as the product of 100 is not strictly less than k.