Problem Description
Given an array of positive integers and an integer k, count the number of contiguous subarrays such that the product of all the elements in the subarray is strictly less than k.
Key Insights
- Using a sliding window approach is effective when dealing with contiguous subarrays and maintaining a running product.
- Since the problem involves multiplying numbers, as soon as the running product exceeds or equals k, shrink the window from the left.
- The number of valid subarrays ending at the current right pointer is given by the length of the window.
Space and Time Complexity
Time Complexity: O(n) because each element is visited at most twice. Space Complexity: O(1) as only a few extra variables are used.
Solution
The solution uses a sliding window technique to maintain a running product of the subarray.
- Initialize pointers for the window (left) and variables for the running product (prod) and count of valid subarrays (ans).
- Iterate through the array with a right pointer, multiplying the current element to the product.
- If the product becomes greater than or equal to k, move the left pointer rightwards while dividing the product by each element passed.
- The number of subarrays ending at the current index that satisfy the condition is equal to (right - left + 1). Add this count to ans.
- Return the final count stored in ans.
This method efficiently tracks valid subarrays and avoids checking all possible combinations.