Member-only story
Given an array, find the greatest value who’s numbers frequency is the same number as itself.
Example:
Input: [1,1,2,2,3,3]
Output: 2
It’s important to divide and conquere when working on algorithmic codes. This problem requires 3 steps.
- Create a frequency table
- Sort array in decending order
- Iterate over the array until a hash key equals its value.
var findLucky = function(arr) {
let hash = {}
arr.forEach(num => {
hash[num]? hash[num]++ : hash[num] = 1
})
arr.sort((a,b) => b - a)
for(let i = 0; i < arr.length; i++){
if(hash[arr[i]] === arr[i]){
return arr[i]
}
}
return -1
};
Further analysing, we can cut down on our runtime by eliminating the .sort
method and instead using a temporary variable and returning it like so:
var findLucky = function(arr) {
let hash = {}
arr.forEach(num => {
hash[num]? hash[num]++ : hash[num] = 1
})
let temp = -1
for(let i = 0; i < arr.length; i++){
if(hash[arr[i]] === arr[i]){
if(arr[i] > temp){
temp = arr[i]
}
}
}
return temp
};