Strings: Making Anagrams

  • + 2 comments

    Hey susmithamenda,

    The reason why it doesn’t work is because in:

    for(int value: count.values()){
            if(value != 0){
                numberNeeded++;
            }
        }
    

    You are not considering if the value > 1. You are just assuming that both strings are unique in characters. For instance, if value is “2” or “-2” - it is still being treated as only if value = 1 (numberNeeded++).

    Secondly, another problem with this code is when the second string is iterating through the map. It is possible that you delete a previous entry that you have already done.

    for(char c : second.toCharArray()){
            if(count.containsKey(c))
                count.put(c, count.get(c)-1);
            else
                count.put(c, 1);
        }
    

    For example:

    First: “d” Second: “ccc”

    After adding it to map (first for loop): Map: <”d”, 1>

    After the checking map in second for loop:

    first iteration: Map: <”d”, 1> <"c", 1>

    second iteration: (DELETED A PREVIOUS ENTRY HERE) Map: <”d”, 1> <"c", 0>

    third iteration Map: <”d”, 1> <"c", -1>

    Hope that helps, Cheers