Java HashMap interview programs: word count, most frequent element and group anagrams

Three HashMap problems, from easy to a true interview favourite: count the words in a sentence, find the element that appears most often, and group anagrams together. Along the way you'll learn getOrDefault, merge, entrySet and computeIfAbsent for good.

Grouping anagrams. Six words, eat, tea, tan, ate, nat and bat, each have their letters sorted into a key: eat, tea and ate become aet (yellow), tan and nat become ant (blue), and bat becomes abt (green). Dashed lines lead each key into a HashMap of String to List of String with three entries: aet holds eat, tea, ate; ant holds tan, nat; abt holds bat. A dark bar shows computeIfAbsent(key, k -> new ArrayList<>()).
Fig. 1 — Words with the same letters share the same sorted key, so they land in the same bucket.

If you could learn only one data structure for coding interviews, it would be the HashMap. It answers “how many?”, “have I seen this?” and “which group does this belong to?”, and it does each in O(1) time on average.

You already used one in Phase 2 to count characters. This phase goes further: counting words, finding a winner, and building groups.

The four HashMap methods you need

Method What it does Example
getOrDefault(k, d) the value for k, or d if there isn’t one map.getOrDefault(word, 0)
merge(k, v, fn) put v if k is new, otherwise combine old and new with fn map.merge(word, 1, Integer::sum)
entrySet() every key and value together, for looping for (var e : map.entrySet())
computeIfAbsent(k, fn) the value for k; if missing, create it with fn first map.computeIfAbsent(key, k -> new ArrayList<>())

16. Count word frequency

Problem: count each word in "java spring java kafka spring java".

java=3
spring=2
kafka=1

Plan: split the sentence into words, then count them exactly like you counted characters.

String text = "java spring java kafka spring java";
Map<String, Integer> count = new LinkedHashMap<>();

for (String word : text.trim().split("\\s+")) {
    count.put(word, count.getOrDefault(word, 0) + 1);
}

for (Map.Entry<String, Integer> e : count.entrySet()) {
    System.out.println(e.getKey() + "=" + e.getValue());
}

Why split("\\s+") and not split(" ")? Real input has double spaces, tabs and new lines. \\s+ means “one or more whitespace characters”, so any gap counts as one separator. Look at the difference:

"  java  spring ".split(" ")             // [, , java, , spring]   empty strings!
"  java  spring ".trim().split("\\s+")   // [java, spring]

The trim() removes the leading spaces; otherwise split gives you one empty string at the start.

Follow-ups:

  • Ignore case? Count word.toLowerCase().
  • Ignore punctuation, like “java,” and “java.”? Clean first: text.replaceAll("[^a-zA-Z ]", "").
  • Print the most common words first? That’s sorting a map by value, problem 22.

Cost: O(n) time for n words.

17. Find the most frequent element

Problem: in [1, 3, 2, 3, 4, 3, 2], the number 3 appears 3 times, more than any other.

Plan: count everything in a map. Then walk the map and keep track of the best key and its count, exactly like finding the max in problem 1.

int[] nums = {1, 3, 2, 3, 4, 3, 2};

Map<Integer, Integer> freq = new HashMap<>();
for (int n : nums) {
    freq.merge(n, 1, Integer::sum);
}

int best = nums[0];
int bestCount = 0;
for (Map.Entry<Integer, Integer> e : freq.entrySet()) {
    if (e.getValue() > bestCount) {
        best = e.getKey();
        bestCount = e.getValue();
    }
}
System.out.println(best + " appears " + bestCount + " times");   // 3 appears 3 times

Read merge(n, 1, Integer::sum) out loud like this: “for key n, put 1; if there’s already a value, add 1 to it”. It does the same job as the getOrDefault line, in one call.

One pass instead of two

merge returns the new value, so you can track the winner while counting:

Map<Integer, Integer> freq = new HashMap<>();
int best = nums[0], bestCount = 0;
for (int n : nums) {
    int c = freq.merge(n, 1, Integer::sum);
    if (c > bestCount) {
        best = n;
        bestCount = c;
    }
}

What about ties? If two numbers both appear 3 times, which one wins? In the one-pass version, the one that reaches the top count first wins. In the two-pass version with a HashMap, it depends on the map’s internal order, so it’s unpredictable. If the interviewer cares, ask: “On a tie, should I return the smallest value, or the one that appeared first?” Then code that rule.

Cost: O(n) time, O(k) space for k distinct values.

18. Group anagrams

Problem: group these words so that anagrams are together:

["eat", "tea", "tan", "ate", "nat", "bat"]
[[eat, tea, ate], [tan, nat], [bat]]

This is a famous one (LeetCode 49) and a very common Java interview question, because it needs a map whose values are lists.

The idea: what do eat, tea and ate have in common? Sort their letters and all three become aet. So the sorted letters make a perfect key. Words with the same key belong in the same group.

Plan:

  1. For each word, sort its letters to get the key.
  2. Look up the key in a Map<String, List<String>>. If there’s no list yet, create an empty one.
  3. Add the word to that list.
  4. At the end, the map’s values are the groups.
String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};
Map<String, List<String>> groups = new LinkedHashMap<>();

for (String w : words) {
    char[] chars = w.toCharArray();
    Arrays.sort(chars);
    String key = new String(chars);

    groups.computeIfAbsent(key, k -> new ArrayList<>()).add(w);
}

System.out.println(groups);
// {aet=[eat, tea, ate], ant=[tan, nat], abt=[bat]}

List<List<String>> result = new ArrayList<>(groups.values());
System.out.println(result);
// [[eat, tea, ate], [tan, nat], [bat]]

computeIfAbsent, slowly

That one line replaces all of this:

List<String> list = groups.get(key);
if (list == null) {
    list = new ArrayList<>();
    groups.put(key, list);
}
list.add(w);

computeIfAbsent(key, k -> new ArrayList<>()) means: “give me the list for this key; if there isn’t one, make a new empty list, store it, and give me that”. It always returns a list you can .add to. It’s the standard way to build a “map of lists” in modern Java, and interviewers notice when you use it.

Why new String(chars) and not chars.toString()? chars.toString() gives you something like [C@1b6d3586, the array’s memory label, not its letters. Every word would get a different key and nothing would group. A classic bug.

A faster key

Sorting each word costs O(k log k) for a word of length k. You can build the key from a letter count instead, which is O(k):

int[] count = new int[26];
for (char c : w.toCharArray()) count[c - 'a']++;
String key = Arrays.toString(count);   // "[1, 0, 0, 0, 1, ...]"

Same groups, slightly faster for long words. Mention it as an option; most interviewers are happy with the sorted key.

Cost: O(n · k log k) time for n words of up to k letters, and O(n · k) space for the map.

What you practised

  • Counting anything with getOrDefault or merge
  • Looping over keys and values with entrySet()
  • Tracking a winner while you loop, and asking about ties
  • Building a map of lists with computeIfAbsent
  • Designing a key so that things that belong together collide on purpose

Next: Phase 5, sorting with Comparator: sort employees by salary, by salary then age, and finally sort that word-count map by its values.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.