
Problem Statement
Given a list of strings, the task is to group the anagrams together.
An anagram is a word or phrase formed by rearranging the letters of another, such as "cinema", formed from "iceman"
You can return the answer in any order.
Examples
Example 1:
- Input:
["dog", "god", "hello"] - Output:
[["dog", "god"], ["hello"]] - Justification: "dog" and "god" are anagrams, so they are grouped together. "hello" does not have any anagrams in the list, so it is in its own group.
Example 2:
- Input:
["listen", "silent", "enlist"] - Output:
[["listen", "silent", "enlist"]] - Justification: All three words are anagrams of each other, so they are grouped together.
Example 3:
- Input:
["abc", "cab", "bca", "xyz", "zxy"] - Output:
[["abc", "cab", "bca"], ["xyz", "zxy"]] - Justification: "abc", "cab", and "bca" are anagrams, as are "xyz" and "zxy".
Constraints:
- 1 <= strs.length <= 10<sup>4</sup>
0 <= strs[i].length <= 100strs[i]consists of lowercase English letters.
Solution
-
Sorting Approach:
- For each word in the input list:
- Sort the letters of the word.
- Use the sorted word as a key in a hash map, and add the original word to the list of values for that key.
- The hash map values will be the groups of anagrams.
- For each word in the input list:
-
Why This Will Work:
- Anagrams will always result in the same sorted word, so they will be grouped together in the hash map.
Algorithm Walkthrough
Let's trace the third example, ["abc", "cab", "bca", "xyz", "zxy"]. Move through the steps one at a time:
Step 1. Checking every pair of words against each other gets slow quickly. Instead give each word a key that all of its anagrams share, and let words with the same key fall into the same group. Sorting the letters is exactly such a key: it throws away the order, which is the only thing anagrams disagree about, and keeps the letters, which is what they agree about. That turns "is this an anagram of that" into "is this key equal to that key", which is a single lookup.
1 of 7
Code
Complexity Analysis
- Time Complexity: O(n*k*log(k)), where n is the number of strings, and k is the maximum length of a string in strs. This is because each of the n strings is sorted in O(k*log(k)) time.
- Space Complexity: O(n*k), where n is the number of strings, and k is the maximum length of a string in strs. This space is used for the output data structure and the hash map.