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.
Example 1:
Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
Example 2:
Input: nums = [1,2,3], k = 0
Output: 0
Constraints:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
Solutions
Solution 1: Two Pointers
We can use two pointers to maintain a sliding window, where the product of all elements in the window is less than $k$.
Define two pointers $l$ and $r$ pointing to the left and right boundaries of the sliding window, initially $l = r = 0$. We use a variable $p$ to record the product of all elements in the window, initially $p = 1$.
Each time, we move $r$ one step to the right, adding the element $x$ pointed to by $r$ to the window, and update $p = p \times x$. Then, if $p \geq k$, we move $l$ one step to the right in a loop and update $p = p \div \text{nums}[l]$ until $p < k$ or $l \gt r$. Thus, the number of contiguous subarrays ending at $r$ with a product less than $k$ is $r - l + 1$. We then add this number to the answer and continue moving $r$ until $r$ reaches the end of the array.
The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.