• + 0 comments

    Java

    public static int migratoryBirds(List<Integer> arr) {
        // Write your code here
        
            if(arr == null || arr.isEmpty()) return 0;
            if(arr.size() == 1) return arr.get(0);
    
            Map<Integer, Integer> counterMap = new HashMap<>();
            int maxFrequency = 0;
            int result = Integer.MAX_VALUE;
            for(Integer bird : arr){
                counterMap.put(bird, counterMap.getOrDefault(bird, 0) + 1);
                Integer frequency = counterMap.get(bird);
                if(frequency > maxFrequency){
                    maxFrequency = frequency;
                    result = bird;
                }
    
                if(frequency == maxFrequency){
                    result = Math.min(result, bird);
                }
            }
    
        return result;
    
    }