- Related Questions & Answers
- Subarray Product Less Than K in C++
- Sum of two elements just less than n in JavaScript\n
- Count all subsequences having product less than K in C++
- Count ordered pairs with product less than N in C++
- Left right subarray sum product - JavaScript
- Subarray with the greatest product in JavaScript
- Find Smallest Letter Greater Than Target in JavaScript
- Maximum Product Subarray in Python
- Find maximum product of digits among numbers less than or equal to N in C++
- What is Less than Operator (<) in JavaScript?
- Maximum sum subarray having sum less than or equal to given sums in C++
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++
- Maximum Product Subarray | Added negative product case in C++
- Count pairs in a sorted array whose product is less than k in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

Following is the code −

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));

8

Advertisements