Group strings that are anagrams
Company: J.P. Morgan
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Onsite
Quick Answer: This question evaluates skills in string manipulation, grouping by character composition, and the use of hashing or sorting techniques to construct keys while reasoning about time and space trade-offs.
Constraints
- 0 <= len(strs) <= 100000
- 0 <= len(strs[i]) <= 100
- Each string contains only lowercase English letters 'a' to 'z'
Examples
Input: (["eat", "tea", "tan", "ate", "nat", "bat"],)
Expected Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
Explanation: "eat", "tea", and "ate" are anagrams; "tan" and "nat" are anagrams; "bat" stands alone.
Input: (["", "b", ""],)
Expected Output: [["", ""], ["b"]]
Explanation: Both empty strings belong to the same group, and that group appears first because the first element is an empty string.
Input: ([],)
Expected Output: []
Explanation: An empty input list produces no groups.
Input: (["ab", "ba", "ab", "cd", "dc", "e"],)
Expected Output: [["ab", "ba", "ab"], ["cd", "dc"], ["e"]]
Explanation: Duplicate strings are allowed and remain in the same anagram group in their original order.
Input: (["abc"],)
Expected Output: [["abc"]]
Explanation: A single string forms a group by itself.
Hints
- You need a way to map every string to an anagram signature so that all anagrams produce the same key.
- A sorted version of the string works as a key, but with lowercase letters only, a 26-character frequency count can be even more efficient.