In this post solution written in Swift for Migratory Bird Practice challenge from HackerRank. The problem statement goes like this - "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"
For Example, Given array [1, 1, 2, 3, 3] There are two each of types 1 and 3, and one sighting of type 2. Pick the lower of the two types seen twice: type 1.
Working solution in Swift 5.0:
func migratoryBirds(arr: [Int]) -> Int {
// Write your code here
var dict:[String: Int] = [:]
// 1
arr.forEach({
let stringKey = "\($0)"
if dict[stringKey] == nil {
dict[stringKey] = 1
} else {
dict[stringKey] = dict[stringKey]! + 1
}
})
// 2
var minKey = -1
var maxValue = -1
dict.keys.sorted().forEach({
// 3
if dict[$0]! > maxValue {
maxValue = dict[$0]!
minKey = Int($0)!
}
})
return minKey
}
1. Create a dictionary (hashmap) of bird type vs sightings. For first encounter always add entry of fresh key other wise just increment sighting count.
2. Keep track of maximum sighting and also the corresponding minimum type of bird.
3. Note the sorted keys to ascending. Thus save max sighting count & return it's type.