# Migratory Birds

# Migratory Birds

+ 106 comments Since a lot of codes shared are complicated as well as sub-optimal. Here's a simple, concise and optimal approach for coders looking for an elegant solution :

input() count = [0]*6 for t in map(int,input().strip().split()): count[t] += 1 print(count.index(max(count)))

The solution is

**and traverses the given list only once.**

### For aspiring programmers :

Be careful while learning from the codes you read. I haven't checked for all languages, but a lot of python-codes here, are even

**incorrect**(including the**editorial**as well as currently topvoted comment). Particularly for this problem, be cautious if you see usage of "set", "dictionary" or "Counter" anywhere.Dictionaries/sets are unordered in python, which means one cannot trust the outcome where order matters. In fact, these solutions would always give wrong result for simple testcase like

`2, 2, 1, 1`

in Python 3.6. Thus, as programmers we need to ensure that our code succeeds always, and not only by chance !

+ 33 comments My Java 8 Solution

static int migratoryBirds(int n, int[] ar) { // Complete this function int ary[] = new int[n]; for(int i = 0; i < n ; i++ ) ary[ar[i]]++; int max = 0,maxpos=0; for(int i = 0 ; i < n ; i++) { if(ary[i] > max) { max = ary[i]; maxpos = i; } } return maxpos; }

+ 6 comments Using python collections FTW.

import sys from collections import Counter n = int(input().strip()) types = list(map(int, input().strip().split(' '))) birds = Counter(types) # Counts the array into a dictionary print(birds.most_common(1)[0][0])

+ 8 comments ### Java solution - passes 100% of test cases

From my HackerRank solutions.

import java.util.Scanner; // Time Complexity: O(n) public class Solution { static final int NUM_TYPES = 5; static int migratoryBirds(int[] birds) { /* Get counts of each type */ int[] count = new int[NUM_TYPES + 1]; for (int num : birds) { count[num]++; } /* Find max */ int maxIndex = 1; for (int i = 0; i < count.length; i++) { if (count[i] > count[maxIndex]) { maxIndex = i; } } return maxIndex; } public static void main(String[] args) { /* Save input */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] birds = new int[n]; for (int i = 0; i < n; i++){ birds[i] = scan.nextInt(); } scan.close(); /* Calculate result */ int result = migratoryBirds(birds); System.out.println(result); } }

+ 6 comments Python oneline (not optimal, though)

print(sorted(reversed(list(set(types))), key=types.count)[-1])

Sort 2843 Discussions, By:

Please Login in order to post a comment