Group Anagrams Using Hash Map in DSA Python - Time & Space Complexity
We want to understand how the time needed to group anagrams grows as the list of words gets bigger.
Specifically, how does the program's work increase when we add more words or longer words?
Analyze the time complexity of the following code snippet.
from collections import defaultdict
def group_anagrams(words):
anagrams = defaultdict(list)
for word in words:
sorted_word = ''.join(sorted(word))
anagrams[sorted_word].append(word)
return list(anagrams.values())
This code groups words that are anagrams by sorting each word and using the sorted word as a key in a hash map.
- Primary operation: Looping over each word and sorting each word.
- How many times: The loop runs once for every word (n times), and sorting runs once per word on its length (k times).
As the number of words (n) grows, the program sorts each word of length (k) every time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (words) | 10 x sorting each word (k log k) |
| 100 (words) | 100 x sorting each word (k log k) |
| 1000 (words) | 1000 x sorting each word (k log k) |
Pattern observation: The work grows linearly with the number of words, and sorting each word depends on its length.
Time Complexity: O(n x k log k)
This means the time grows linearly with the number of words and depends on sorting each word's letters.
[X] Wrong: "Sorting all words is just O(n) because we only loop once."
[OK] Correct: Sorting each word takes extra time depending on word length, so total time depends on both number of words and their length.
Understanding this time complexity helps you explain how your solution scales with input size, a key skill in interviews.
"What if we used character count arrays instead of sorting each word? How would the time complexity change?"
Practice
Solution
Step 1: Understand anagrams
Anagrams are words with the same letters in different orders.Step 2: Use sorted strings as keys
Sorting letters of each word gives a common key for all anagrams.Final Answer:
Use sorted strings as keys to group words with the same letters -> Option CQuick Check:
Sorted string key groups anagrams = C [OK]
- Using string length as key groups wrong words
- Using first or last character misses many anagrams
- Not sorting letters before using as key
Solution
Step 1: Identify dictionary initialization
In Python, an empty dictionary is created with curly braces {}.Step 2: Check other options
List uses [], set uses set(), tuple uses (). Only {} is dictionary.Final Answer:
anagrams = {} -> Option AQuick Check:
Empty dictionary = {} [OK]
- Using [] which creates a list, not a dictionary
- Using set() which creates a set, not a dictionary
- Using () which creates a tuple, not a dictionary
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
anagrams = {}
for word in words:
key = ''.join(sorted(word))
if key not in anagrams:
anagrams[key] = []
anagrams[key].append(word)
print(list(anagrams.values()))Solution
Step 1: Sort each word and group
Words "eat", "tea", "ate" sorted become "aet"; grouped together. "tan", "nat" sorted "ant"; grouped. "bat" sorted "abt"; alone.Step 2: Collect groups in dictionary values
Values are lists of grouped anagrams: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]Final Answer:
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']] -> Option AQuick Check:
Sorted keys group words correctly = A [OK]
- Appending words to wrong keys
- Not sorting words before grouping
- Mixing groups or missing words
words = ["abc", "bca", "cab"]
anagrams = {}
for word in words:
key = sorted(word)
if key not in anagrams:
anagrams[key] = []
anagrams[key].append(word)
print(anagrams)Solution
Step 1: Check key type used in dictionary
sorted(word) returns a list, but lists are not hashable and cannot be dictionary keys.Step 2: Fix by converting list to string or tuple
Use key = ''.join(sorted(word)) or key = tuple(sorted(word)) to make hashable key.Final Answer:
sorted(word) returns a list, which cannot be used as a dictionary key -> Option DQuick Check:
Dictionary keys must be hashable, list is not [OK]
- Using list as dictionary key causes TypeError
- Not converting sorted result to string or tuple
- Ignoring error messages about unhashable types
words = ["listen", "silent", "enlist", "google", "gogole", "abc"], which code snippet correctly groups the anagrams and returns the groups sorted alphabetically by their first word?Solution
Step 1: Group words by sorted key using dictionary
anagrams = {} for w in words: key = ''.join(sorted(w)) anagrams.setdefault(key, []).append(w) groups = list(anagrams.values()) groups.sort(key=lambda x: x[0]) print(groups) uses sorted word as key and appends words to list correctly.Step 2: Sort groups by first word
anagrams = {} for w in words: key = ''.join(sorted(w)) anagrams.setdefault(key, []).append(w) groups = list(anagrams.values()) groups.sort(key=lambda x: x[0]) print(groups) sorts the list of groups by the first word in each group, meeting requirement.Final Answer:
Correctly groups anagrams using sorted keys, setdefault, append, and sorts groups by first word -> Option BQuick Check:
Group by sorted key + sort groups by first word = A [OK]
- Using word itself as key loses grouping
- Overwriting dictionary values instead of appending
- Using list instead of dictionary for grouping
Ready to prove it?
Pass the test and this pattern moves unknown
