Product of subarray just less than target in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first argument, and a number, target, as the second argument.

Our function is supposed to count and return the number of (contiguous) subarrays where the product of all the elements in the subarray is less than target.

For example, if the input to the function is

Input

const arr = [10, 5, 2, 6];
const target = 100;

Output

const output = 8;

Output Explanation

The 8 subarrays that have product less than 100 are −

[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].

Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.

Example

Following is the code −

 Live Demo

const arr = [10, 5, 2, 6];
const target = 100;
const countSubarrays = (arr = [], target = 1) => {
   let product = 1
   let left = 0
   let count = 0
   for (let right = 0; right < arr.length; right++) {
      product *= arr[right]
      while (left <= right && product >= target) {
         product /= arr[left]
         left += 1
      }
      count += right - left + 1
   }
   return count
};
console.log(countSubarrays(arr, target));

Output

8

Updated on: 24-Apr-2021

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements