Monday, 26 August 2019

Migratory Birds Hacker Rank Solution in C

Problem:

https://www.hackerrank.com/challenges/migratory-birds/problem


#include <stdio.h> int main() { int n,i,max,ans; scanf("%d", &n); int a[n],h[6]={0}; for(i = 0; i < n; i++) { scanf("%d",&a[i]); h[a[i]]++; } max=h[1]; for(i = 2; i < 6; i++) { if(max<h[i]) { max=h[i]; ans=i; } } printf("%d",ans); return 0; }

11 comments:

  1. why is 6 in h[6] please explain.

    ReplyDelete
    Replies
    1. Read the question properly..there are only 5 types of birds and they are 1,2,3,4,5

      Delete
  2. Replies
    1. assuming max= count of type 1 birds (h[1])
      because in the question in the input format, it is written as there can be only birds of type1,type2,type3, type4 and type5 only. There is no type 0 bird

      Delete
  3. Could you please explain, what do you mean by "h[a[i]]++;", and why you wrote there?

    ReplyDelete
  4. where is the condition specified in the case there are 2 two types of birds with same number of most migrations and the lower ID bird is displayed

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. For example : max=3, ans=1, i=2 and h[2]=3
      Now the condition is if(max < h[i]) => if(3 < 3) is false and ans is not updated to 2. In this way ans will always store the lowerId when 2 type birds are same in number.
      To understand the code, you must know hashing or frequency table concept ma

      Delete
  5. This comment has been removed by the author.

    ReplyDelete