Finding degree of subarray in an array JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

The degree of an array of literals is defined as the maximum frequency of any one of its elements.

const arr = [1, 2, 3, 3, 5, 6, 4, 3, 8, 3];

The degree of this array is 4, because 3 is repeated 4 times in this array.

We are required to write a JavaScript function that takes in an array of literals. The task of our function is to find the length of the smallest continious subarray from the array whose degree is same as of the whole array.

Example

const arr = [1, 2, 3, 3, 5, 6, 4, 3, 8, 3];
const findShortestSubArray = (arr = []) => {
   let range = new Map(), maxDegree = 0, minLength = Infinity;
   for(let i = 0; i < arr.length; i++){ if(range.has(arr[i])) {
      let start = range.get(arr[i])[0];
      let degree = range.get(arr[i])[2]; degree++;
      range.set(arr[i], [start, i, degree]);
      if(degree > maxDegree)
         maxDegree = degree;
      }
      else {
         let degree = 1;
         range.set(arr[i],[i, i, degree]); if(degree > maxDegree)
         maxDegree = degree;
      }
   }
   for (let key of range.keys()){
      let val = range.get(key)
      if(val[2] === maxDegree){
         let diff = (val[1] - val[0]) + 1;
         if(diff < minLength) minLength = diff;
      }
   }
   return minLength;
};
console.log(findShortestSubArray(arr));

Output

And the output in the console will be −

8
raja
Published on 21-Nov-2020 06:39:50
Advertisements