• + 0 comments

    Here is my O(n) solution using Java 8 HashMaps

    public static int migratoryBirds(List<Integer> arr) {
            Map<Integer, Integer> map = new HashMap<>();
            int count;      // counter for number of sightings
            int max = 0;    // to track the highest number of sightings
            int minID = Integer.MAX_VALUE; // to track the smallest ID
            
            for(int i = 0; i < arr.size(); i++) {
                count = map.getOrDefault(arr.get(i), 0) + 1; // get the current num of sightings for the ID and increment, defaults as 1 if the ID is not present in the map.
                map.put(arr.get(i), count); //update the number of sightings using ID as key
                if(max < count) {   // if the highest num of sightings is less than the current num of sightings  
                    max = count;    // update max num of sightings. 
                    minID = arr.get(i); // update the smallest ID
                } else if(count == max && arr.get(i) < minID) { // of the current num of sightings == max numbers of sightings AND the current ID is less than the minimum ID
                    minID = arr.get(i); // update the smallest ID only. 
                }
            }
            return minID;
        }