Leetcode 713. Subarray Product Less Than K
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
.
nums
will be between 1
and 3 * 10^4
.nums
will be between 1
and 1000
.k
will be between 1
and 10^6
.k
is less than or equal to 1, there can’t be any valid subarray since all elements in the array are at least 1. We should return 0
in such cases.k
.To solve this problem efficiently, we can use a sliding window (or two-pointer) technique. Here’s the plan:
left
and right
, to represent the current window of subarrays.product
will keep track of the product of all elements in the current window.right
pointer from the start to the end of the array.right
pointer position, multiply product
by nums[right]
.product
is greater than or equal to k
, move the left
pointer to the right and divide product
by nums[left]
to shrink the window.right
and starting from any position between left
and right
are valid subarrays. Thus, add right - left + 1
to the count of valid subarrays.public class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
if (k <= 1) return 0;
int product = 1, count = 0, left = 0;
for (int right = 0; right < nums.length; right++) {
product *= nums[right];
while (product >= k) {
product /= nums[left];
left++;
}
count += right - left + 1;
}
return count;
}
}
right
pointer and at most once by the left
pointer). Thus, the time complexity is O(n), where n is the length of the array.This approach ensures that we efficiently count all subarrays with a product less than k
by leveraging the sliding window technique to keep the product of the current window in check.
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?