01
Problem Statement
Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all elements is strictly less than k.
- A subarray is a contiguous sequence; we count how many such subarrays satisfy product <
k. - In the classic version,
numscontains only positive integers; ifk <= 1, no positive product can be < k, so return 0. - If the array can contain zeros or negatives, the problem changes (product can become zero or negative; counting valid subarrays requires different handling).
02
Key Observations
- For positive-only arrays, expanding the window increases the product and shrinking decreases it. So for each
right, we can shrinkleftuntil the product of[left..right]is less thank; then every subarray ending atrightwith start in[left, right]has product < k — that isright - left + 1subarrays. - We maintain the product of the current window; when we add
nums[right], we multiply; when we shrink, we divide bynums[left]. - If
k <= 1, we never have a positive product < k, so the answer is 0.
03
Approach
High-level: For each right, find the smallest left such that the product of [left..right] is < k. Then all subarrays ending at right with start in [left, right] are valid; add right - left + 1 to the count.
Steps:
- If
k <= 1, return 0. Initializeleft = 0,prod = 1,count = 0. - For each
right:prod *= nums[right]. Whileprod >= k, divideprodbynums[left]andleft++. - Add
right - left + 1tocount(all subarrays ending atrightwith start in[left, right]). - Return
count.
04
Implementation
Java
public int numSubarrayProductLessThanK(int[] nums, int k) {
if (k <= 1) {
return 0;
}
int left = 0, prod = 1, count = 0;
for (int right = 0; right < nums.length; right++) {
prod *= nums[right];
while (prod >= k) {
prod /= nums[left++];
}
count += right - left + 1;
}
return count;
}05
Test Cases
Example 1
Input
nums = [10,5,2,6], k = 100
Expected
8Explanation
8 subarrays have product < 100.
06
Complexity Analysis
- Time: O(n).
- Space: O(1).
07
Follow-ups
- What if elements can be zero or negative?