Ken
Ken

Reputation: 17

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);
    }
}

Upvotes: 0

Views: 110

Answers (3)

dani-vta
dani-vta

Reputation: 7130

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

Upvotes: 0

Elie Azoury
Elie Azoury

Reputation: 46

you are overiding the increment instead of :

 if(map.containsKey(arr[i])){
            map.put(arr[i],map.get(arr[i])+1);
        }
        map.put(arr[i], 1);

do

 if(map.containsKey(arr[i])){
                map.put(arr[i],map.get(arr[i])+1);
            }
            else map.put(arr[i], 1);

Upvotes: 0

Chetan Ahirrao
Chetan Ahirrao

Reputation: 1602

Missing else

if(map.containsKey(arr[i])){
            map.put(arr[i],map.get(arr[i])+1);
        }
else
        map.put(arr[i], 1);

That's why your elements are being initialized with frequency 1 each time instead of incrementing. So output is 5+3+2=10

Upvotes: 0

Related Questions