Open In App

Number of subarrays having product less than K

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of positive numbers, calculate the number of possible contiguous subarrays having product lesser than a given number K.

Examples : 

Input : arr[] = [1, 2, 3, 4] 
            K = 10
Output : 7
The subarrays are {1}, {2}, {3}, {4}, {1, 2}, {1, 2, 3} and {2, 3}

Input  : arr[] = [1, 9, 2, 8, 6, 4, 3] 
             K = 100
Output : 16

Input  : arr[] = [10, 5, 2, 6]  
             K = 100
Output : 8

One naive approach to this problem is to generate all subarrays of the array and then count the number of arrays having product less than K. 

Below is the implementation of the above approach : 

C++




// CPP program to count subarrays having
// product less than k.
#include <iostream>
using namespace std;
 
int countsubarray(int array[], int n, int k)
{
    int count = 0;
    int i, j, mul;
 
    for (i = 0; i < n; i++) {
        // Counter for single element
        if (array[i] < k)
            count++;
 
        mul = array[i];
 
        for (j = i + 1; j < n; j++) {
            // Multiple subarray
            mul = mul * array[j];
            // If this multiple is less
            // than k, then increment
            if (mul < k)
                count++;
            else
                break;
        }
    }
 
    return count;
}
 
// Driver Code
int main()
{
    int array[] = { 1, 2, 3, 4 };
    int k = 10;
    int size = sizeof(array) / sizeof(array[0]);
    int count = countsubarray(array, size, k);
    cout << count << "\n";
}
 
// This code is contributed by  'Dev Agarwal'.


Java




// Java program to count subarrays
// having product less than k.
class GFG {
    static int countsubarray(int array[], int n, int k)
    {
        int count = 0;
        int i, j, mul;
 
        for (i = 0; i < n; i++) {
 
            // Counter for single element
            if (array[i] < k)
                count++;
 
            mul = array[i];
 
            for (j = i + 1; j < n; j++) {
 
                // Multiple subarray
                mul = mul * array[j];
 
                // If this multiple is less
                // than k, then increment
                if (mul < k)
                    count++;
                else
                    break;
            }
        }
 
        return count;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int array[] = { 1, 2, 3, 4 };
        int k = 10;
        int size = array.length;
 
        int count = countsubarray(array, size, k);
        System.out.print(count);
    }
}
 
// This code is contributed by Sam007


Python3




# Python3 program to count subarrays
# having product less than k.
 
 
def countsubarray(array, n, k):
    count = 0
    for i in range(0, n):
 
        # Counter for single element
        if array[i] < k:
            count += 1
 
        mul = array[i]
 
        for j in range(i + 1, n):
 
            # Multiple subarray
            mul = mul * array[j]
 
            # If this multiple is less
            # than k, then increment
            if mul < k:
                count += 1
            else:
                break
    return count
 
 
# Driver Code
array = [1, 2, 3, 4]
k = 10
size = len(array)
count = countsubarray(array, size, k)
print(count, end=" ")
 
# This code is contributed by Shreyanshi Arun.


C#




// C# program to count subarrays having
// product less than k.
using System;
 
public class GFG {
 
    static int countsubarray(int[] array, int n, int k)
    {
        int count = 0;
        int i, j, mul;
 
        for (i = 0; i < n; i++) {
 
            // Counter for single element
            if (array[i] < k)
                count++;
 
            mul = array[i];
 
            for (j = i + 1; j < n; j++) {
 
                // Multiple subarray
                mul = mul * array[j];
 
                // If this multiple is less
                // than k, then increment
                if (mul < k)
                    count++;
                else
                    break;
            }
        }
 
        return count;
    }
 
    // Driver Code
    static public void Main()
    {
        int[] array = { 1, 2, 3, 4 };
        int k = 10;
        int size = array.Length;
 
        int count = countsubarray(array, size, k);
 
        Console.WriteLine(count);
    }
}
 
// This code is contributed by vt_m.


PHP




<?php
// PHP program to count subarrays
// having  product less than k.
 
// function that returns count
function countsubarray($array, $n, $k)
{
    $count = 0;
 
    for ($i = 0; $i < $n; $i++)
    {
         
        // Counter for single element
        if ($array[$i] < $k)
            $count++;
 
        $mul = $array[$i];
 
        for ($j = $i + 1; $j < $n; $j++)
        {
             
            // Multiple subarray
            $mul = $mul * $array[$j];
             
            // If this multiple is less
            // than k, then increment
            if ($mul < $k)
                $count++;
            else
                break;
        }
    }
 
    return $count;
}
 
// Driver Code
$array = array(1, 2, 3, 4);
$k = 10;
$size = sizeof($array);
$count = countsubarray($array, $size, $k);
echo($count . "\n");
 
// This code is contributed by Ajit.
?>


Javascript




<script>
// javascript program to count subarrays
// having product less than k.
 
    function countsubarray(array , n , k)
    {
        var count = 0;
        var i, j, mul;
 
        for (i = 0; i < n; i++)
        {
 
            // Counter for single element
            if (array[i] < k)
                count++;
 
            mul = array[i];
            for (j = i + 1; j < n; j++)
            {
 
                // Multiple subarray
                mul = mul * array[j];
 
                // If this multiple is less
                // than k, then increment
                if (mul < k)
                    count++;
                else
                    break;
            }
        }
        return count;
    }
 
    // Driver Code
     
        var array = [ 1, 2, 3, 4 ];
        var k = 10;
        var size = array.length;
 
        var count = countsubarray(array, size, k);
        document.write(count);
 
// This code is contributed by todaysgaurav
</script>


Output

7

Time complexity: O(n^2).
Auxiliary Space: O(1)

We can optimized approach is based on sliding window technique (Note that we need to find contiguous parts)
Firstly, according to the description, all elements in the array are strictly positive. Also let’s assume that the product of all array elements always fits in 64-bit integer type. Taking these two points into consideration, we are able to multiply and divide array’s elements safety (no division by zero, no overflows).

Let’s see how to count the desired amount. Assume, we have a window between start and end, and the product of all elements of it is p < k. Now, let’s try to add a new element x. 

There are two possible cases.

Case 1. p*x < k 
This means we can move the window’s right bound one step further. How many contiguous arrays does this step produce? It is: 1 + (end-start).
Indeed, the element itself comprises an array, and also we can add x to all contiguous arrays which have right border at end. There are as many such arrays as the length of the window.

Case 2. p*x >= k
This means we must first adjust the window’s left border so that the product is again less than k. After that, we can apply the formula from Case 1.

Example :  

  a = [5, 3, 2]
  k = 16
 
  counter = 0
  Window: [5]
  Product: 5

  5  counter += 1+ (0-0)
  counter = 1
  Window: [5,3]
  Product: 15

  15  counter += 1 + (1-0)
  counter = 3
  Window: [5,3,2]
  Product: 30

  30 > 16 --> Adjust the left border
  New Window: [3,2]
  New Product: 6

  6  counter += 1 + (2-1)
  counter = 5
  Answer: 5 

Implementation:

C++





Java





Python3





C#





PHP




<?php
// PHP program to count
// subarrays having product
// less than k.
 
function countSubArrayProductLessThanK($a,$k)
{
    $n = count($a);
    $p = 1;
    $res = 0;
    for ($start = 0, $end = 0;
         $end < $n; $end++)
    {
 
        // Move right bound by 1
        // step. Update the product.
        $p *= $a[$end];
         
        // Move left bound so guarantee
        // that p is again less than k.
        while ($start < $end &&
               $p >= $k)
            $p /= $a[$start++];
         
        // If p is less than k, update
        // the counter. Note that this
        // is working even for (start == end):
        // it means that the previous
        // window cannot grow anymore
        // and a single array element
        // is the only addendum.
        if ($p < $k)
        {
            $len = $end - $start + 1;
            $res += $len;
        }
    }
 
    return $res;
}
 
// Driver Code
echo countSubArrayProductLessThanK(
             array(1, 2, 3, 4), 10) . "\n";
echo countSubArrayProductLessThanK(
             array(1, 9, 2, 8, 6, 4, 3), 100) . "\n";
echo countSubArrayProductLessThanK(
             array(5, 3, 2), 16) . "\n";
echo countSubArrayProductLessThanK(
             array(100, 200), 100) . "\n";
echo countSubArrayProductLessThanK(
             array(100, 200), 101) . "\n";
     
// This code is contributed by mits
?>


Javascript





Output

7
16
5
0
1

Complexities: Every element in the array is accessed at most two times, therefore, it is O(n) time complexity. A few scalar variables are used, therefore, it is O(1) extra space.

Exercise 1: Update the solution so that it could handle nils in the input array. 
Exercise 2: Update the solution so that it could handle multiplication overflow when computing products.



Last Updated : 20 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads