
Problem
Solution
Submissions
Group Anagrams using HashMap
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a Java program to group anagrams together from an array of strings. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. You need to return the anagrams grouped together in a list of lists.
Example 1
- Input: strs = ["eat","tea","tan","ate","nat","bat"]
- Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
- Explanation:
- Step 1: Create a HashMap to store groups of anagrams with sorted strings as keys.
- Step 2: For each string, sort its characters to create a key (e.g., "eat" becomes "aet").
- Step 3: Add the original string to the list mapped to its sorted key.
- Step 4: Group "eat", "tea", and "ate" together as they all sort to "aet".
- Step 5: Group "tan" and "nat" together as they both sort to "ant".
- Step 6: "bat" sorts to "abt" and forms its own group.
- Step 7: Return all the groups as a list of lists.
Example 2
- Input: strs = [""]
- Output: [[""]]
- Explanation:
- Step 1: Create a HashMap to store groups of anagrams.
- Step 2: For the empty string, its sorted form is also an empty string.
- Step 3: Add the empty string to the list mapped to the empty string key.
- Step 4: Return a list containing a single group with an empty string.
Constraints
- 1 ≤ strs.length ≤ 10^4
- 0 ≤ strs[i].length ≤ 100
- strs[i] consists of lowercase English letters
- Time Complexity: O(n * k), where n is the length of strs and k is the maximum length of a string in strs
- Space Complexity: O(n * k) for storing all strings
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use a HashMap where the key is a representation of the anagram and the value is a list of strings that are anagrams
- For each string, create a sorted version to use as a key (since anagrams will have the same sorted string)
- Alternatively, create a count of each character to use as a key
- Add each string to the appropriate list in the HashMap
- After processing all strings, return the values of the HashMap as a list of lists