Group strings that are anagrams
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates string-processing and data-structuring competency, focusing on identifying and grouping anagrams through comparison of unordered character multisets.
Constraints
- 1 <= len(strs) <= 10^4
- 0 <= len(strs[i]) <= 100
- The total number of characters across all strings is <= 10^6
Examples
Input: (["eat", "tea", "tan", "ate", "nat", "bat"],)
Expected Output: [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
Explanation: "eat", "tea", and "ate" are anagrams; "tan" and "nat" are anagrams; "bat" stands alone. Groups and words are sorted for deterministic output.
Input: (["", "", "a"],)
Expected Output: [["", ""], ["a"]]
Explanation: The two empty strings are anagrams of each other, and "a" forms its own group.
Input: (["abc"],)
Expected Output: [["abc"]]
Explanation: A single string forms one group by itself.
Input: (["abc", "bca", "cab", "foo", "ofo", "bar", "abc"],)
Expected Output: [["abc", "abc", "bca", "cab"], ["bar"], ["foo", "ofo"]]
Explanation: All versions of "abc" belong together, "foo" and "ofo" are anagrams, and "bar" is alone.
Hints
- Anagrams share the same character signature. Think about how to turn each word into a key that will be identical for all its anagrams.
- Because the strings only contain lowercase English letters, a 26-length frequency count can be used as a hashable grouping key.