Lonely Integer

  • + 0 comments

    JAVA code using hashmap

     public static int lonelyinteger(List<Integer> a) {
    // Write your code here
        // Create a hashmap to store the frequency of each element
        HashMap<Integer, Integer> frequencyMap = new HashMap<>();
    
        // Populate the hashmap with element frequencies
        for (int num : a) {
            frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
        }
    
        // Find and return the element with a frequency of 1
        for (int key : frequencyMap.keySet()) {
            if (frequencyMap.get(key) == 1) {
                return key;
            }
        }
       return -1;
    }
    

    }