Array & Hashing
52. Group Anagrams
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.
Examples
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 <= 10^4
- 0 <= strs[i].length <= 100
strs[i]consists of lowercase English letters.
# Group Anagrams
# Given a list of strings, group the anagrams together.
# Anagrams are words that share the same letters (e.g., "eat" and "tea").
palabras = ["eat","tea","tan","ate","nat","bat"]
res = {} # key: sorted letters as tuple, value: list of anagrams
for palabra in palabras:
# Sort the letters to create a common key for all anagrams
letras = tuple(sorted(palabra))
if letras in res:
res[letras].append(palabra)
else:
res[letras] = [palabra]
print(list(res.values())) Keyboard shortcuts
← h Previous problem
→ l Next problem
Esc Back to index
? Toggle this help