Group Anagrams — LeetCode #49
Given an array of strings strs
, group the anagrams together. You can return the answer in any order.
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.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i]
consists of lowercase English letters.
Solutions:
Python
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# Create a dictionary to store the anagrams
anagrams = {}
# Loop through each string in the list
for s in strs:
# Sort the string alphabetically
sorted_string = ''.join(sorted(s))
# If the sorted string is not a key in the dictionary, add it
# with an empty list as the value
if sorted_string not in anagrams:
anagrams[sorted_string] = []
# Add the original string to the list of anagrams for the sorted string
anagrams[sorted_string].append(s)
# Return the list of anagrams
return anagrams.values()
C#
public class Solution {
public IList<IList<string>> GroupAnagrams(string[] strs) {
// Create a dictionary to store the anagrams
Dictionary<string, List<string>> anagrams = new Dictionary<string, List<string>>();
// Loop through each string in the list
foreach (string s in strs)
{
// Sort the string alphabetically
string sortedString = string.Join("", s.OrderBy(c => c).ToArray());
// If the sorted string is not a key in the dictionary, add it
// with an empty list as the value
if (!anagrams.ContainsKey(sortedString))
{
anagrams[sortedString] = new List<string>();
}
// Add the original string to the list of anagrams for the sorted string
anagrams[sortedString].Add(s);
}
// Return the list of anagrams
return anagrams.Values.Cast<IList<string>>().ToList();
}
}
Java
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// Create a map to store the anagrams
Map<String, List<String>> anagrams = new HashMap<>();
// Loop through each string in the list
for (String s : strs) {
// Sort the string alphabetically
char[] sortedChars = s.toCharArray();
Arrays.sort(sortedChars);
String sortedString = new String(sortedChars);
// If the sorted string is not a key in the map, add it
// with an empty list as the value
if (!anagrams.containsKey(sortedString)) {
anagrams.put(sortedString, new ArrayList<>());
}
// Add the original string to the list of anagrams for the sorted string
anagrams.get(sortedString).add(s);
}
// Return the list of anagrams
return new ArrayList<>(anagrams.values());
}
}
Javascript
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
// Create a dictionary to store the anagrams
const anagrams = {};
// Loop through each string in the list
for (const s of strs) {
// Sort the string alphabetically
const sortedString = s.split('').sort().join('');
// If the sorted string is not a key in the dictionary, add it
// with an empty array as the value
if (!(sortedString in anagrams)) {
anagrams[sortedString] = [];
}
// Add the original string to the array of anagrams for the sorted string
anagrams[sortedString].push(s);
}
// Return the list of anagrams
return Object.values(anagrams);
};
Typescript
function groupAnagrams(strs: string[]): string[][] {
// Create a dictionary to store the anagrams
const anagrams: { [key: string]: Array<string> } = {};
// Loop through each string in the list
for (const s of strs) {
// Sort the string alphabetically
const sortedString = s.split('').sort().join('');
// If the sorted string is not a key in the dictionary, add it
// with an empty array as the value
if (!(sortedString in anagrams)) {
anagrams[sortedString] = [];
}
// Add the original string to the array of anagrams for the sorted string
anagrams[sortedString].push(s);
}
// Return the list of anagrams
return Object.values(anagrams);
};
PHP
class Solution {
/**
* @param String[] $strs
* @return String[][]
*/
function groupAnagrams($strs) {
// Create a dictionary to store the anagrams
$anagrams = [];
// Loop through each string in the list
foreach ($strs as $s) {
// Sort the string alphabetically
$sortedString = str_split($s);
sort($sortedString);
$sortedString = implode('', $sortedString);
// If the sorted string is not a key in the dictionary, add it
// with an empty array as the value
if (!array_key_exists($sortedString, $anagrams)) {
$anagrams[$sortedString] = [];
}
// Add the original string to the array of anagrams for the sorted string
$anagrams[$sortedString][] = $s;
}
// Return the list of anagrams
return array_values($anagrams);
}
}
I hope this helps! Let me know if you have any questions. Don’t forget to follow and give some like to support my content