How I solved Hacker Rank Challenge, Migratory Birds

Danielle Torres
3 min readMay 9, 2021

Hello Everyone,

Today I will be going over how I solved Hacker Rank Challenge, Migratory Birds, using JavaScript.

Objective: Given an array of bird sighting where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.

After reviewing the explanation and output. I decided to use hash maps to solve this challenge. I wanted to be able to store each bird type id and the number of sightings. The following is an example of what my hash would store:

Array = [1, 4, 4, 4, 5, 3];

Hash = {1:1, 4:3, 5:3, 3:1)

From this hash I can determine the highest value. If there are two bird type ids(keys) with the same number of sightings(values) then we want to return the smallest bird type id.

I use a for loop to iterate through the array of bird sightings provided and the has() method to return true or false if the array contains a value that is stored in my hash.

If it does, I use the set() method to increment the value of the hash that share the same bird type id(key).

myHash.set(arr[i], (myHash.get(arr[i]))+1);

If the integer in the array is not currently stored in the hash, then I use the set() method to add the new pair. The bird type id and a sighting of 1.

myHash.set(arr[i], 1);

After the for loop is complete. My hash will look like this:

My Hash Results = {1:1, 4:3, 5:3, 3:1)

Now its time to narrow down the results. I use another for loop and Object.entries to grab the keys and values of my hash and store them in a const variable.

I created two variables, maxValue and setKey, to store my results. While looping if the value (number of sightings) is greater than the maxValue, then I assign the value as the new maxValue and assign the key (bird type id) to setKey.

If the the maxValue is shared between two different bird type ids (keys), then I will assign the lowest key to setKey.

Once the last loop is complete, I return the bird type id (setKey) with the most sightings. Here is the complete code:

function migratoryBirds(arr) {// Write your code herelet myHash = new Map();
let maxValue = 0;
let setKey = 0;
for (let i=0; i < arr.length; i++) {
if (myHash.has(arr[i]) === true) {
myHash.set(arr[i], (myHash.get(arr[i]))+1);} else {
myHash.set(arr[i], 1);}
};
for (const [key, value] of myHash.entries()) {
if (value > maxValue) {
maxValue = value;
setKey = key;} else if

(value === maxValue && setKey > key) {
setKey = key;}
}
return setKey
}

It Passed! I hope everyone finds this helpful and enjoyed the blog. Please let me know what you think. Until next time!

--

--

Danielle Torres

Highly organized & motivated Software Engineer with an application analyst/data analyst background.