10
Jan
2020

Hackerrank Migratory Birds (C++)

C++ :

int migratoryBirds(vector<int> arr) {
    vector<int> frequency(5, 0);
    int highestFrequency = 0, birdtype = -1, typeOfBird = 0;

    for(int i = 0; i < arr.size(); i++){
        birdtype = arr[i];
        frequency[birdtype - 1]++;
    }

    highestFrequency = frequency[0];
    
    for(int j = 1; j < frequency.size(); j++){
        if(highestFrequency < frequency[j]){
            highestFrequency = frequency[j];
            typeOfBird = j;
        }
    }

    typeOfBird += 1;
    return typeOfBird;
}

Explanation:

First, a frequency vector of size 5 is initialized to all 0s. For each type of bird in arr, count the frequency of the bird in the first for loop. In the second for loop, find the highest number of frequency, and assign it to typeOfBird.

Before returning typeOfBird, add 1 to it, as vectors start counting from 0 but type of bird starts from 1.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *