DSA problem
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.
Because every element is a positive integer, the product of a window is a monotonic quantity: extending the window can only increase the product, and shrinking it can only decrease it. This monotonicity is exactly what makes a variable-size sliding window applicable.
The strategy is to maintain a window whose running product stays below k. As you advance the right pointer, multiply its value into the running product. If the product reaches or exceeds k, advance the left pointer and divide out its values until the product drops back below k. For each valid right position, every subarray that ends at right and starts anywhere within the current window is valid, so the window's width (right - left + 1) is the count of new subarrays to add.
Examples
nums = [10,5,2,6], k = 1008nums = [1,2,3], k = 00nums = [1,1,1], k = 26Constraints
- 1 <= nums.length <= 3 * 10^4
- 1 <= nums[i] <= 1000
- 0 <= k <= 10^6
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.