Medium
Group Anagrams
👶 The 5-Year-Old Summary
You have a bunch of word magnets mixed up on the floor. Group together the ones that use the same letters! "eat", "tea", and "ate" all go in the same group!
🎮 Interactive Visualizer
Click "Step" to see words get grouped!
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
Unprocessed words:
Groups (Hash Map):
🧠The Brain Hack
The trick: sort each word! "eat" → "aet", "tea" → "aet", "tan" → "ant". All words with the same sorted version are anagrams! Use sorted word as the hash key.
💻 The Clean Solution
def group_anagrams(strs):
# A box with labeled compartments
groups = {}
# Process each word
for word in strs:
# Sort letters to create a "key"
# "eat" -> "aet", "tea" -> "aet"
key = ''.join(sorted(word))
# Put word in the right compartment
if key not in groups:
groups[key] = []
groups[key].append(word)
# Return all the groups
return list(groups.values())
# Try it!
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(group_anagrams(words))
# Output: [["eat","tea","ate"], ["tan","nat"], ["bat"]]
Time: O(n × k log k) - n words, sorting each takes k log k
Space: O(n × k) - storing all words