Challenge - 5 Problems
Anagram Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Grouping Anagrams by Sorted Key
What is the output of the following Python code that groups anagrams using a hash map with sorted strings as keys?
DSA Python
from collections import defaultdict words = ["eat", "tea", "tan", "ate", "nat", "bat"] groups = defaultdict(list) for word in words: key = ''.join(sorted(word)) groups[key].append(word) result = list(groups.values()) print(result)
Attempts:
2 left
💡 Hint
Think about how sorting each word groups anagrams together.
✗ Incorrect
The code sorts each word to create a key. Anagrams have the same sorted key, so they are grouped together in the dictionary. The final list contains groups of anagrams.
🧠 Conceptual
intermediate1:30remaining
Key Choice for Grouping Anagrams
Which of the following is the best key to use in a hash map to group anagrams efficiently?
Attempts:
2 left
💡 Hint
Anagrams have the same letters in different orders.
✗ Incorrect
Sorting the string puts all letters in order, so anagrams become identical keys. Length or first character alone cannot uniquely identify anagrams. Sum of ASCII values can cause collisions.
🔧 Debug
advanced2:00remaining
Identify the Error in Anagram Grouping Code
What error does the following code produce when grouping anagrams using a hash map?
DSA Python
words = ["bat", "tab", "eat"] groups = {} for word in words: key = sorted(word) if key not in groups: groups[key] = [] groups[key].append(word) print(groups)
Attempts:
2 left
💡 Hint
Check the type of the key used in the dictionary.
✗ Incorrect
The sorted(word) returns a list, which is unhashable and cannot be used as a dictionary key, causing a TypeError.
❓ Predict Output
advanced2:00remaining
Output of Grouping Anagrams Using Character Count as Key
What is the output of this Python code that groups anagrams using character count as the hash map key?
DSA Python
from collections import defaultdict words = ["abc", "bca", "cab", "xyz", "zyx", "yxz"] groups = defaultdict(list) for word in words: count = [0]*26 for ch in word: count[ord(ch) - ord('a')] += 1 groups[tuple(count)].append(word) result = list(groups.values()) print(result)
Attempts:
2 left
💡 Hint
Character count arrays uniquely identify anagrams.
✗ Incorrect
The code counts characters for each word and uses the count tuple as key. Anagrams have identical counts, so they group together.
🧠 Conceptual
expert1:30remaining
Why Use Tuple Instead of List as Hash Map Key in Anagram Grouping?
Why is a tuple preferred over a list as a key in a hash map when grouping anagrams by character count?
Attempts:
2 left
💡 Hint
Dictionary keys must be hashable and immutable.
✗ Incorrect
Lists can change after creation, so they cannot be used as dictionary keys. Tuples cannot change and are hashable, making them valid keys.