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
.
0
.nums
be negative or zero?
nums
array?
nums
can vary, but typically it can be assumed to be reasonably large (e.g., up to (10^4)).k
is less than or equal to 1?
k
is less than or equal to 1, it’s impossible to have any product less than k
since all elements are positive integers. Thus, return 0
.k
.start
and end
, both at the beginning of the array.prod
to keep track of the product of elements in the current window.end
from 0
to the end of the array:
prod
by the value at nums[end]
.prod
becomes greater than or equal to k
, increment start
until prod
is less than k
, adjusting prod
accordingly.end
by adding (end - start + 1)
to the result.def numSubarrayProductLessThanK(nums, k):
if k <= 1:
return 0
start = 0
prod = 1
count = 0
for end in range(len(nums)):
prod *= nums[end]
while prod >= k and start <= end:
prod //= nums[start]
start += 1
count += (end - start + 1)
return count
nums
.
end
and potentially once by start
).This solution efficiently counts the number of valid subarrays with a product less than k
using a sliding window approach. The algorithm runs in linear time, making it suitable for large input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?