Learn how to find the least frequent number from an array.
Given an array with different counts of number we have to find the number with least frequency and return it.
If there are two numbers with same least frequency the return the first number.
Example
Input: [1, 2, 2, 3, 3, 3] [2, 2, 2, 3, 3, 3, 4, 4, 4, 2, 5, 5, 5, 6, 6] Output: 1 6
1
has occurred only once.
6
was least frequent with 2 counts.
Finding the least frequent number from an array.
One way to solve this is by using nested loops to find the elements with least frequency but that will result in O(n ^ 2).
The second way is to use a hash map to keep the count of the elements occurrence in the array and then return the number with least frequency. It is the most efficient method.
Implementation
- Count the frequency of the numbers occurrence and store them in a object.
- Then iterate all the elements of the object and find the number with least frequency.
const leastFrequent = (arr) => { //Store the number counts in object const count = arr.reduce((a, b) => { if (!a[b]) { a[b] = 1; } else { a[b]++; } return a; }, {}); let minCount = Number.MAX_SAFE_INTEGER; let numberWithLeastCount = 0; //Find the number with least count for (const [key, value] of Object.entries(count)) { if (value < minCount) { minCount = value; numberWithLeastCount = key; } } return numberWithLeastCount; }
We have used reduce()
method to count the frequency of array elements and then iterate all the elements of the hash/object using the for...of loop by pulling the key and value of a given object with Object.entries
method.
Input: console.log(leastFrequent([1, 1, 1, 2, 2, 2, 3, 3, 4])); console.log(leastFrequent([2, 2, 2, 3, 3, 3, 4, 4, 4, 2, 5, 5, 5, 6, 6])); Output: 4 6
Time complexity: O(n).
Space complexity: O(n).