In this Migratory Birds HackerRank Problem, Given an array of bird sightings 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.
Example
There are two each of types and , and one sighting of type . Pick the lower of the two types seen twice: type .
Function Description
Complete the migratoryBirds function in the editor below.
migratoryBirds has the following parameter(s):
- int arr[n]: the types of birds sighted
Returns
- int: the lowest type id of the most frequently sighted birds
Input Format
The first line contains an integer, , the size of .
The second line describes as space-separated integers, each a type number of the bird sighted.
Constraints
- It is guaranteed that each type is , , , , or .
Migratory Birds HackerRank Problem Solutions
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in Python 3
def migratoryBirds(arr):
arr.sort()
birds = {}
for x in arr:
if x in birds:
birds[x] += 1
else:
birds[x] = 1
return max(birds, key=birds.get)
Problem Solution in JavaScript
function migratoryBirds(arr) {
const counting = new Array(6).fill(0)
let lowerMostFrequently = [0,0] //id, count
for(let i = 0; i<arr.length;i++){
counting[arr[i]]++
if(lowerMostFrequently[1] < counting[arr[i]] ||
(lowerMostFrequently[1] == counting[arr[i]] &&
lowerMostFrequently[0] > arr[i])
){
lowerMostFrequently = [arr[i],counting[arr[i]]]
}
}
return lowerMostFrequently[0]
}
Migratory Birds Problem Solution in C#
public static int migratoryBirds(List<int> arr)
{
var birdsDict = new Dictionary<int, int>();
for(var i = 0; i < arr.Count; i++){
if(birdsDict.ContainsKey(arr[i])){
birdsDict[arr[i]] ++;
continue;
}
birdsDict.Add(arr[i], 1);
}
var maxSightings = birdsDict.Values.Max();
var minId = birdsDict.Where(x => x.Value == maxSightings).Min(z => z.Key);
return minId;
}
Leave a Reply