Skip to content

Commit 72cc6fe

Browse files
committed
add subarray_product_less_than_k
1 parent 37484b7 commit 72cc6fe

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
Given an array of integers nums and an integer k,
3+
return the number of contiguous subarrays where the product of all the elements in the subarray is
4+
strictly less than k.
5+
6+
The provided code defines a Java class Solution with a method numSubarrayProductLessThanK that counts the number
7+
of subarrays in an input array nums whose product is less than a given threshold k. It uses a sliding window
8+
approach to efficiently compute this count.
9+
10+
Time Complexity:
11+
12+
The code iterates through the nums array once, using two pointers (startWindow and endWindow) to define the
13+
sliding window. This results in a time complexity of O(N), where N is the length of the input array nums.
14+
Space Complexity:
15+
16+
The code uses a constant amount of additional space to store integer variables (startWindow, product, and count).
17+
Therefore, the space complexity is O(1), which means it is independent of the size of the input array.
18+
*/
19+
class Solution {
20+
numSubarrayProductLessThanK(nums, k) {
21+
let startWindow = 0; // The left end of the sliding window
22+
let product = 1; // Initialize product to 1 to accumulate the product
23+
let count = 0; // Count of subarrays with a product less than k
24+
25+
// Iterate through the array using a sliding window approach
26+
for (let endWindow = 0; endWindow < nums.length; endWindow++) {
27+
// Multiply the current element to the product
28+
product *= nums[endWindow];
29+
30+
// Shrink the window by moving the start pointer as long as the product is greater than or equal to k
31+
while (startWindow <= endWindow && product >= k) {
32+
// Divide the product by the element at the start of the window
33+
product /= nums[startWindow];
34+
// Move the start of the window to the right
35+
startWindow++;
36+
}
37+
38+
// Update the count with the number of valid subarrays within the current window
39+
count += endWindow - startWindow + 1;
40+
}
41+
42+
// Return the count, which represents the number of subarrays with a product less than k
43+
return count;
44+
}
45+
}
46+
47+
// Example usage
48+
const solution = new Solution();
49+
const result = solution.numSubarrayProductLessThanK([10, 5, 2, 6], 100);
50+
console.log(result); // Output: 8

0 commit comments

Comments
 (0)