Count frequency of all characters in String

1. Introduction

In this String relation interview question, we are supposed to find the frequency of every character in String.

For example:

InputOutput
“”
” “
“laptop”l=1, a=1, p=2, t=1, o=1
“mississippi”m=1, i=4, s=4, p=2
“God”G=1, o=1, d=1

2. Using HashMap

We will scan the entire String character by character and insert them in HashMap. If the character does not exist in it, then we will set value to 1. If it exists, then we will add 1 to the previous value.

public static Map<Character, Integer> characterCount(String str) {
    if (str == null || str.trim().isEmpty()) {
        return Collections.emptyMap();
    }

    Map<Character, Integer> map = new HashMap<Character, Integer>();
    for (char ch : str.toCharArray()) {
        if (map.containsKey(ch)) {
            map.put(ch, map.get(ch) + 1);
        } else {
            map.put(ch, 1);
        }
    }

    return Collections.unmodifiableMap(map);
}

Remember, the HashMap class doesn’t maintain the order of insertion so the returned Map will not have entries in order of insertion. If you need an order to be maintained, then use LinkedHashMap.

If we print the entries from HashMap, our output is : {p=2, s=4, i=4, m=1}

Entries from LinkedHashMap looks like this : {m=1, i=4, s=4, p=2}

3. Analysis of characterCount method:

  1. Time complexity
    1. O(n) is time complexity where n is the length of the string. We traverse the entire string and populate necessary information into the Map.
  2. Space complexity
    1. O(n) is space complexity where n is the length of the string. In worst case, the entire string contains unique characters, i.e. the count of every character in the string is 1.

4. Conclusion

In this article, we learned about finding the frequency of characters in the string using HashMap and LinkedHashMap.

Leave a Reply

Your email address will not be published. Required fields are marked *