04. Count the subarrays having product less than k
The problem can be found at the following link: Question Link
My Approach
I uses a simple approach with two pointers,
i
andj
.i
represents the starting pointer, andj
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
andj
do not reach the valuen
.During the traversal, we checks whether the subarray between the
starting
andending
pointers has a product less thank
.If the product is greater than or equal to
k
, we updates the value of starting pointeri
to make the current product value less thank
.If the product is less than
k
, we increments theoutput
variable out by the distance betweeni
andj
, representing thesubarray count
.Finally, increments
j
to move the ending pointer to the next element.
Example
Time and Auxiliary Space Complexity
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.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 getlost01/gfg-potd repository.
Last updated