Smallest possible length constituting greatest frequency in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

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

Our function is supposed to find the smallest possible length of a (contiguous) subarray of the array arr, that has the same greatest frequency of any element as the whole array.

For example, if the input to the function is

Input

const arr = [55, 77, 77, 88, 55];

Output

const output = 2;

Output Explanation

The input array has the greatest frequency for any element of 2 because both elements 55 and 77 appear twice.

Of the subarrays that have the greatest frequency as the whole array, the shortest length is 2. So, we return 2.

Example

Following is the code −

 Live Demo

const arr = [55, 77, 77, 88, 55];
const shortestLength = (arr) => {
   let freq = 0
   let len = Infinity
   arr.reduce((acc, num, index) => {
      if (acc[num] !== undefined) {
         acc[num].freq += 1
         acc[num].range[1] = index
      } else {
         acc[num] = {
            freq: 0,
            range: [index, index],
         }
      }
      if (acc[num].freq > freq) {
         freq = acc[num].freq
         len = acc[num].range[1] - acc[num].range[0] + 1
      } else if (acc[num].freq === freq) {
         len = Math.min(
            len,
            acc[num].range[1] - acc[num].range[0] + 1,
         )
      }
      return acc
   }, {})
   return len
};
console.log(shortestLength(arr));

Output

2
raja
Published on 24-Apr-2021 13:45:53
Advertisements