LeetCode 49: Group Anagrams — Step-by-Step Visual Trace
Medium — Hash Table | String | Sorting
The Problem
Group anagrams together from an array of strings, where anagrams are words that contain the same characters in different orders.
Approach
Use a hash map where the key is the sorted version of each word and the value is a list of all words that have the same sorted form. Words with identical sorted characters are anagrams and get grouped together.
Time: O(n * k log k) · Space: O(n * k)
Code
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams_map = {}
for word in strs:
sorted_word = "".join(sorted(word))
if sorted_word in anagrams_map:
anagrams_map[sorted_word].append(word)
else:
anagrams_map[sorted_word] = [word]
return list(anagrams_map.values())
Watch It Run
Try it yourself: Open TraceLit and step through every line.
Built with TraceLit — the visual algorithm tracer for LeetCode practice.
Comments