Start learning free

LESSON 224 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Letter Count in Java: Counting Characters with a HashMap

Practice Read the full explanation

Given a string word, return a HashMap that maps each letter of word to the number of times it appears in word.

Every letter of word is a key, and its value is how many times that letter appears. The order of the entries doesn't matter.

 

Example 1:

Input: word = "banana"
Output: {"b": 1, "a": 3, "n": 2}
Explanation: "b" appears once, "a" three times and "n" twice.

Example 2:

Input: word = "hello"
Output: {"h": 1, "e": 1, "l": 2, "o": 1}
Explanation: "l" appears twice; every other letter appears once.

Example 3:

Input: word = "a"
Output: {"a": 1}
Explanation: A single letter appears once.

 

Constraints:

  • word has at least one letter.
  • word is made of lowercase English letters, a to z.
  • Only the letters of word are keys: a letter that doesn't appear has no entry.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Letter Count in Java, explained

    Problem overview

    The method letterCount receives a string, word, and returns a HashMap<Character, Integer> that maps each letter of the word to the number of times it appears. Only letters that occur get an entry.

    For "banana" the map holds b once, a three times and n twice. Printed, it looks like {a=3, b=1, n=2}. For "hello" it is {e=1, h=1, l=2, o=1}, and for "a" it is {a=1}. The order of the entries doesn't matter: a HashMap doesn't promise any order, so don't rely on the order you see when printing.

    Approach: a counting dictionary

    A map is the right tool whenever the answer is "how many of each". The key is the thing you count, the letter, and the value is the running total. Read the letters one at a time. A letter you have already seen gets its total raised by one. A new letter gets an entry that starts at 1. At the end, every letter of the word has an entry with its full count.

    Step by step

    1. Create the map. HashMap<Character, Integer> counts = new HashMap<>(); starts empty. Generic types can't be primitives, so the key type is Character, the object version of char, and the value type is Integer. Java converts between char and Character, and between int and Integer, automatically.
    2. Loop over the characters. A String can't be used in an enhanced for loop directly. word.toCharArray() returns a char[] with one element per character, and that can be.
    3. Check whether the letter is a key. counts.containsKey(letter) is true when the letter has been seen before. If so, put the letter again with counts.get(letter) + 1. put on an existing key replaces its value.
    4. Otherwise start at 1. In the else branch, counts.put(letter, 1) creates the entry for a first occurrence.
    5. Return the map after the loop.

    The solution in Java

    class Solution {
        public HashMap<Character, Integer> letterCount(String word) {
            HashMap<Character, Integer> counts = new HashMap<>();
            for (char letter : word.toCharArray()) {
                if (counts.containsKey(letter)) {
                    counts.put(letter, counts.get(letter) + 1);
                } else {
                    counts.put(letter, 1);
                }
            }
            return counts;
        }
    }
    

    Java details that matter here:

    • Why the else is needed. get returns null for a missing key. For "banana", counts.get('z') gives null. Adding 1 to that null would throw a NullPointerException, because Java tries to unbox it into an int. The containsKey check makes sure get only runs for keys that exist.
    • A shorter form. counts.put(letter, counts.getOrDefault(letter, 0) + 1); does the same in one line. getOrDefault returns the default, here 0, when the key is missing. counts.getOrDefault('z', 0) on the "banana" map gives 0.
    • Character keys. The loop variable is a primitive char, and it is boxed into a Character when it goes into the map. Two boxed characters with the same letter are equal as map keys, so every a lands on the same entry.
    • No order. Iterating over counts may give the entries in an order unrelated to their position in the word. If you need the order of first appearance, use a LinkedHashMap.

    Tracing "banana"

    This is the map after each letter of "banana" has been handled:

    b -> {b=1}
    a -> {a=1, b=1}
    n -> {a=1, b=1, n=1}
    a -> {a=2, b=1, n=1}
    n -> {a=2, b=1, n=2}
    a -> {a=3, b=1, n=2}
    

    The first a takes the else branch and creates the entry. The second and third take the if branch and raise it to 2 and then 3. The method does nothing more than repeat this decision once per letter.

    The merge method is another compact way to write the same update: counts.merge(letter, 1, Integer::sum) stores 1 for a new key and adds 1 to an existing one. On "banana" it also ends with {a=3, b=1, n=2}. The explicit if and else in the lesson show each case separately, which makes the logic easier to follow the first time.

    Complexity

    Time: O(n) for a word of n letters. Each letter takes a constant number of map operations on average.

    Space: O(k), where k is the number of different letters. With lowercase English letters, k is at most 26, however long the word is.

    Using the result

    The map answers questions about the word directly. After letterCount("banana"), get('a') is 3 and size() is 3, the number of different letters. A letter that isn't in the word gives null from get, so check with containsKey or use getOrDefault before doing arithmetic on the answer.

    Edge cases and common mistakes

    • Calling get without checking. The first time a letter appears, counts.get(letter) + 1 fails with a NullPointerException.
    • Using String keys by mistake. The method's return type is HashMap<Character, Integer>. A HashMap<String, Integer> is a different type and won't compile as the return value.
    • Counting every letter of the alphabet. Only letters that appear are keys. A letter with count 0 shouldn't have an entry.
    • Resetting a count. Calling counts.put(letter, 1) for every letter, without the containsKey check, leaves every count at 1.

    Testing

    • "banana" gives {a=3, b=1, n=2}.
    • "hello" gives {e=1, h=1, l=2, o=1}.
    • "a" gives {a=1}.

    Printing a map shows key=value pairs in braces. The order you see on your machine may differ from the lists above; the entries are the same.

    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free