Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the hash map for grouping anagrams.
DSA Typescript
const map = new Map<string, string[]>(); for (const word of words) { const sorted = word.split('').sort().join(''); if (!map.has([1])) { map.set(sorted, []); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using the original word as the key instead of the sorted word.
Using the map object itself as the key.
✗ Incorrect
We use the sorted version of the word as the key in the map to group anagrams together.
2fill in blank
mediumComplete the code to add the current word to the correct group in the map.
DSA Typescript
map.get(sorted)!.[1](word);Attempts:
3 left
💡 Hint
Common Mistakes
Using pop or shift which remove elements instead of adding.
Using unshift which adds to the start, but push is more common here.
✗ Incorrect
We use push to add the current word to the array of anagrams for the sorted key.
3fill in blank
hardFix the error in the code to return the grouped anagrams as an array of arrays.
DSA Typescript
return Array.from(map.[1]());
Attempts:
3 left
💡 Hint
Common Mistakes
Using keys() which returns the sorted strings.
Using entries() which returns key-value pairs.
✗ Incorrect
We want the values of the map, which are arrays of anagrams, so we use values().
4fill in blank
hardFill both blanks to complete the function that groups anagrams.
DSA Typescript
function groupAnagrams(words: string[]): string[][] {
const map = new Map<string, string[]>();
for (const word of words) {
const sorted = word.split('').[1]().join('');
if (!map.has(sorted)) {
map.set(sorted, []);
}
map.get(sorted)!.[2](word);
}
return Array.from(map.values());
}Attempts:
3 left
💡 Hint
Common Mistakes
Using reverse instead of sort.
Using pop instead of push.
✗ Incorrect
We sort the characters to get the key and push the word into the array for that key.
5fill in blank
hardFill all three blanks to create a concise one-liner that groups anagrams.
DSA Typescript
const groupAnagrams = (words: string[]): string[][] => {
const map = new Map<string, string[]>();
for (const word of words) {
const key = word.split('').[1]().join('');
map.set(key, (map.get(key) || []).[2](word) && map.get(key) || [word]);
}
return Array.from(map.[3]());
};Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push.
Using keys instead of values for the final return.
✗ Incorrect
Sort characters for key, push word into array, and return map values as grouped anagrams.
