Parts of array with n different elements in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of literals, arr, as the first argument. The second argument to our function will be a number, num. Our function should count and return the number of subarrays of the array that contains exactly num distinct elements.

For example, if the input to the function is −

const arr = [12, 15, 12, 15, 18];
const num = 2;

Then the output should be −

const output = 7;

Output Explanation

Subarrays formed with exactly 2 different elements −

[12,15], [15,12], [12,15], [15,18], [12,15,12], [15,12,15], [12,15,12,15]

Example

The code for this will be −

 Live Demo

const arr = [12, 15, 12, 15, 18];
const num = 2;
const distinctSubarrays = (arr = [], num = 1) => {
   const findDistinct = (count) => {
      const map = {};
      let ptr = 0;
      let distinct = 0;
      let res = 0;
      for(let right = 0; right < arr.length; right++){
         const num = arr[right];
         map[num] = (map[num] || 0) + 1;
         if(map[num] === 1){
            distinct += 1;
         };
         while(distinct > count){
            map[arr[ptr]] -= 1;
            if(map[arr[ptr]] === 0){
               distinct -= 1;
            };
            ptr += 1;
         };
         res += right - ptr + 1;
      };
      return res;
   };
   return findDistinct(num) - findDistinct(num - 1)
};
console.log(distinctSubarrays(arr, num));

Output

And the output in the console will be −

7
raja
Published on 09-Apr-2021 08:32:22
Advertisements