- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Smallest possible length constituting greatest frequency in JavaScript
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 −
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
- Related Articles
- Greatest sum and smallest index difference in JavaScript
- Finding difference of greatest and the smallest digit in a number - JavaScript
- All possible odd length subarrays JavaScript
- Return the greatest possible product of n numbers from the array in JavaScript
- Sum of All Possible Odd Length Subarrays in JavaScript
- Finding the greatest and smallest number in a space separated string of numbers using JavaScript
- Smallest possible number divisible by all numbers from 1 to n in JavaScript
- Explain the greatest and the smallest comparing numbers.
- Length of the longest possible consecutive sequence of numbers in JavaScript
- Find the Length of the Longest possible palindrome string JavaScript
- Count all prefixes in given string with greatest frequency using Python
- Find frequency of smallest value in an array in C++
- Function to find the length of the second smallest word in a string in JavaScript
- Program to find kth smallest n length lexicographically smallest string in python
- Write the smallest and the greatest number: $30900,\ 30594,\ 30495,\ 30945$.

Advertisements