Coding
Algorithms

Group Anagrams

Difficulty

Read the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.

Available in Python and C++. You are solving it in Python. Switch to C++

A Voleon quant researcher technical screen opened with this problem in 2026. It is the warm-up before the statistics: the interviewer wants to see you reach for the right data structure without being told, and move on in a few minutes.

Two words are anagrams when one is a rearrangement of the other, so they use the same letters the same number of times. Given a list of lowercase words, group the words that are anagrams of each other.

Implement group_anagrams(words) returning a list of groups, where each group is a list of words. Order the groups by the first appearance of any of their members in the input, and keep the words inside a group in input order. A word that appears twice is two separate entries in the same group. The empty string is an anagram of itself. An empty input returns an empty list.

Examples

group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
# [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]

group_anagrams(["ab", "ba", "ab"])
# [["ab", "ba", "ab"]]  (the repeat is a second entry, not a merge)

Constraints

  • Up to \(2 \times 10^5\) words, each of length at most 12, over the letters a to z only.
  • Words may repeat, may be empty, and may be a single letter.
  • Comparing every word to every other word, or scanning every group so far for each new word, will not finish in time on the largest hidden test. Think about what one value computed per word would let you look a group up directly.

In C++

std::vector<std::vector<std::string>> group_anagrams(
    const std::vector<std::string>& words);

The words arrive as a std::vector<std::string> and the result is one vector per group, in the same order rules as above.

Rate this problem
Language:
Python 3.12C++23
group_anagrams
Rate this problem