javaarrayscollectionshashmapfrequency

How to calculate the sum of odd frequency elements in array using hashmap


Gievn following array arr[] = {5,3,3,3,3,5,5,2}, I have to produce the sum of only the elements with an odd frequency. My output should be 7, i.e. the sum of 5 + 2.

For some reason, I am getting 10 and I don't understand why.

public class OddnumberOfElements {
    public static void main(String[] args) {
        int arr[] = {5, 3, 3, 3, 3, 5, 5, 2};
        LinkedHashMap<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
        for (int i = 0; i < arr.length; i++) {
            if (map.containsKey(arr[i])) {
                map.put(arr[i], map.get(arr[i]) + 1);
            }
            map.put(arr[i], 1);
        }
        int sum = 0;
        for (Map.Entry<Integer, Integer> e : map.entrySet()) {
            if (e.getValue() % 2 != 0) {
                sum = sum + e.getKey();
            }
        }
        System.out.println(sum);
    }
}

Solution

  • In your first for loop, when you're counting the frequency of each int, you're correctly making sure to increment the frequency if the corresponding value is already contained in the Map. However, you forgot to place the opposite case (a new value encountered) in an else branch. In fact, after incrementing each frequency, you're resetting it to 1.

    Your loop could be written like so:

    for (int i = 0; i < arr.length; i++) {
        if (map.containsKey(arr[i])) {
            map.put(arr[i], map.get(arr[i]) + 1);
        } else {
            map.put(arr[i], 1);
        }
    }
    

    Another approach could employ java streams.

    int arr[] = {5, 3, 3, 3, 3, 5, 5, 2};
    Integer sum = Arrays.stream(arr)
            .boxed()
            .collect(Collectors.groupingBy(Integer::intValue, Collectors.counting())) //Creating a hashmap with the frequency of each int
            .entrySet().stream() //Streaming the map's entries
            .filter(e -> e.getValue() % 2 == 1) //for each entry only the ones with an odd frequency are kept
            .collect(Collectors.summingInt(e -> e.getKey())); //Summing the the integers with an odd frequency