Question presented to candidate:
"Given a list of strings, group the anagrams together and return the groups in any order — for example ["eat", "tea", "tan", "ate", "nat", "bat"] becomes [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]. Please solve it in Python and give me the complexity."
What a strong answer should cover:
- The idea of a canonical key shared by all anagrams, and a hash map from key to list of words, built in one pass.
- Two keys: the sorted letters, O(k log k) per word, and a 26-letter count, O(k) per word; total O(n · k log k) or O(n · k).
- O(n · k) space for keys and output, and why the pairwise brute force is O(n² · k).
- Python specifics:
collections.defaultdict(list); keys must be hashable, so"".join(sorted(w))ortuple(...), never a list;dictpreserves insertion order, so groups come out in first-seen order. - Edge cases: empty list, empty string, same letters with different counts.
Clarifying questions expected:
- Only lowercase
a–z? Does the output order matter?
Code / implementation expected: Yes — a group_anagrams(words) function in Python using a dict/defaultdict, run on the sample and on edge cases.