04. Count the subarrays having product less than k
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
I uses a simple approach with two pointers, i
and j
. i
represents the starting pointer, and j
represents the ending pointer.
A variable currProd
is used to store the current product of elements in the subarray.
The code traverses through the array until both i
and j
do not reach the value n
.
During the traversal, we checks whether the subarray between the starting
and ending
pointers has a product less than k
.
If the product is greater than or equal to k
, we updates the value of starting pointer i
to make the current product value less than k
.
If the product is less than k
, we increments the output
variable out by the distance between i
and j
, representing the subarray count
.
Finally, increments j
to move the ending pointer to the next element.
Time Complexity : O(2n)
since we used two pointers here which in worst case can iterate for 2n times.
Auxiliary Space Complexity : constant
auxiliary space complexity as it does not require any extra space.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.