medium Group Anagrams
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 <= 104
0 <= strs[i].length <= 100strs[i]consists of lowercase English letters.
Try it yourself
Try solving this question here:
✅ Solution Group Anagrams
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 <= 104
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
- Given the input
["abc", "cab", "bca", "xyz", "zxy"] - For "abc":
- Sorted word is "abc".
- Add "abc" to the hash map with key "abc".
- For "cab":
- Sorted word is "abc".
- Add "cab" to the list in the hash map with key "abc".
- Continue this process for all words.
- The hash map values are the groups of anagrams.
Code
import java.util.*;
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// Map to hold sorted word as key and list of words as value
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] characters = str.toCharArray();
Arrays.sort(characters);
String sorted = new String(characters);
// If the sorted word is not already a key in the map, add it with a new list as its value
if (!map.containsKey(sorted)) {
map.put(sorted, new ArrayList<>());
}
// Add the original word to the list of values for the sorted word key
map.get(sorted).add(str);
}
// Return the values of the map as a list of lists
return new ArrayList<>(map.values());
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(
sol.groupAnagrams(new String[] { "dog", "god", "hello" })
);
System.out.println(
sol.groupAnagrams(new String[] { "listen", "silent", "enlist" })
);
System.out.println(
sol.groupAnagrams(new String[] { "abc", "cab", "bca", "xyz", "zxy" })
);
}
}
Complexity Analysis
- Time Complexity:
, 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 time. - Space Complexity:
, 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.
🤖 Don't fully get this? Learn it with Claude
Stuck on Group Anagrams? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Group Anagrams** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Group Anagrams** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Group Anagrams**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Group Anagrams**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.