Member-only story

Finding a ‘Lucky Integer’

Jack
1 min readOct 5, 2020

--

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.

  1. Create a frequency table
  2. Sort array in decending order
  3. 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
};

--

--

Jack
Jack

Written by Jack

Magician, Mathematician, and Software Engineer

No responses yet