Migratory Birds Hackerrank Solution

In migratory birds hackerrank problem we need to help study the population of birds migrating across the continent. Each type of bird we are interested in identified by an integer value. We add the id number in the array of sightings whenever a bird of particular type is spotted. We need to find out which type of bird is most commonly sighted. Our task is to print the type number of that bird and if two or more types of birds are equally common, then we choose the type with the smallest ID number.

For example, assume our bird sightings are of types arr=[1,1,2,2,3]. There are two each of types 1 and 2, and one sighting of type 3. Pick the lower of the two types seen twice: type 1.

**How To Think:**

We get an array with the sighting details of migratory birds. Now, we know that when a bird is spotted, its type is pushed into the array. So, if arr = [1,4,4,4,5,3], means that 1 bird of type 1, 3 birds of type 4, 1 bird of type 5 and 1 bird of type 3 are spotted.

Now, we have to find the bird with most common or most number of sighting. So, in this case we know that type 4 has 3 birds and thus it should be the answer. So, if we are able to count the no. of birds of each type in the array and return the type with maximum no. of count, then it should be the answer.

**How To Code:**

Since, till now its clear the we just need to maintain count of each type and return the one with maximum no. of count. Now, point is how to do that. One possible way is to take an array of size 5 (since, type can be maximum till 5) in which index represent type and value at that index represents, count of that type. Since, type can be 1,2,3,4 and 5 and index of array starts at 0, we map 0 index to type 1, 1 index to type 2 and so on.

Now we run a loop to calculate the frequency of each type of the bird in the array ar and store it in the array f. Once this array is filled, we just need to find the maximum of these counts and return the answer.

```
#include <bits/stdc++.h>
using namespace std;
int migratoryBirds(int n, vector <int> ar) {
// Complete this function
int f[5];
for(int i=1;i<=5;i++)
{
int c=0;
for(int j=0;j<n;j++)
{
if(ar[j]==i)
{
c++;
}
f[i-1]=c;
}
}
int max=f[0],loc=0;
for(int k=1;k<5;k++)
{
if(f[k]>max)
{
max=f[k];
loc=k;
}
}
return (loc+1);
}
int main() {
int n;
cin >> n;
vector<int> ar(n);
for(int ar_i = 0; ar_i < n; ar_i++){
cin >> ar[ar_i];
}
int result = migratoryBirds(n, ar);
cout << result << endl;
return 0;
}
```

## One comment: On Migratory Birds Hackerrank Problem Solution

saiplease write the code in c