- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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

- 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
- Program to find sum of two numbers which are less than the target in Python
- Find Smallest Letter Greater Than Target in JavaScript
- 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 Product Subarray in Python
- Find maximum product of digits among numbers less than or equal to N in C++
- Number of elements less than or equal to a given number in a given subarray in C++
- Smallest prime number just greater than the specified number in JavaScript

Advertisements