LeetCode 49: Group Anagrams Solution
Master LeetCode problem 49 (Group Anagrams), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
49. Group Anagrams
Problem Explanation
Explanation:
To group anagrams together, we can use a hashmap where the key is a sorted version of each word, and the value is a list of anagrams that match the sorted key. We iterate through each word in the input array, sort it, and then add it to the corresponding list in the hashmap. Finally, we return the values of the hashmap as the grouped anagrams.
-
Algorithm:
- Initialize a hashmap to store the grouped anagrams.
- Iterate through each word in the input array.
- Sort the characters of the word and use it as a key in the hashmap.
- If the key is not present in the hashmap, add it with a new list.
- Add the word to the list corresponding to the key.
- Return the values of the hashmap as the grouped anagrams.
-
Time Complexity: O(n * k * log k) where n is the number of words and k is the maximum length of a word.
-
Space Complexity: O(n * k) for the hashmap.
:
Solution Code
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
String sortedStr = new String(charArray);
if (!map.containsKey(sortedStr)) {
map.put(sortedStr, new ArrayList<>());
}
map.get(sortedStr).add(str);
}
return new ArrayList<>(map.values());
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 49 (Group Anagrams)?
This page provides optimized solutions for LeetCode problem 49 (Group Anagrams) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 49 (Group Anagrams)?
The time complexity for LeetCode 49 (Group Anagrams) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 49 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 49 in Java, C++, or Python.