The sliding window approach allows us to efficiently find subarrays where the product is less than k
. By maintaining a window (two pointers), we can dynamically adjust the size of the current subarray based on the product of its elements. As the window size grows, the product is updated; if it exceeds k
, we reduce the window from the left until the product is again less than k
. This method minimizes redundant calculations.
Time Complexity: O(n)
- Each element is processed at most twice.
Space Complexity: O(1)
- Only a constant amount of extra space is used.
1public class Solution {
2 public int numSubarrayProductLessThanK(int[] nums, int k) {
3 if (k <= 1) return 0;
4 int prod = 1, count = 0, left = 0;
5 for (int right = 0; right < nums.length; right++) {
6 prod *= nums[right];
7 while (prod >= k) prod /= nums[left++];
8 count += right - left + 1;
9 }
10 return count;
11 }
12}
In this Java implementation, we maintain a product of the current subarray elements and dynamically adjust the window using two indices right
and left
. We ensure the product is below k
by adjusting left
, adding valid subarrays to the count.
The brute force approach involves checking every possible subarray within nums
and calculating their products. Each subarray is counted if its product is less than k
. Though less efficient, it guarantees correctness by examining all potential subarrays.
Time Complexity: O(n^2)
- Considers all possible subarrays.
Space Complexity: O(1)
- Constant extra space used.
1public class Solution {
2 public int numSubarrayProductLessThanK_bruteforce(int[] nums, int k) {
3 if (k <= 1) return 0;
4 int count = 0;
5 for (int start = 0; start < nums.length; start++) {
6 int prod = 1;
7 for (int end = start; end < nums.length; end++) {
8 prod *= nums[end];
9 if (prod >= k) break;
10 count++;
11 }
12 }
13 return count;
14 }
15}
This Java method checks each potential subarray from a starting point, quickly abandoning further checks if a subarray's product meets or exceeds k
. It uses nested loops to achieve this inspection of each subarray.