Group Anagrams Using Hash Map in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to group anagrams grows as the list of words gets bigger.
How does the program's work increase when we add more words or longer words?
Analyze the time complexity of the following code snippet.
function groupAnagrams(strs: string[]): string[][] {
const map = new Map();
for (const word of strs) {
const sorted = word.split('').sort().join('');
if (!map.has(sorted)) {
map.set(sorted, []);
}
map.get(sorted)!.push(word);
}
return Array.from(map.values());
}
This code groups words that are anagrams by sorting each word and using the sorted word as a key in a map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each word and sorting its letters.
- How many times: Once for each word in the list.
As the number of words grows, the program sorts each word, so work grows with both number of words and word length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 words, length 5 | About 10 x sorting 5 letters |
| 100 words, length 5 | About 100 x sorting 5 letters |
| 1000 words, length 5 | About 1000 x sorting 5 letters |
Pattern observation: The total work grows roughly linearly with the number of words, but sorting each word depends on its length.
Time Complexity: O(n * k log k)
This means the time grows with the number of words (n) times the cost to sort each word of length k.
[X] Wrong: "Sorting each word is constant time, so total time is just O(n)."
[OK] Correct: Sorting depends on word length k, so sorting each word takes about k log k time, not constant.
Understanding this helps you explain how hashing and sorting combine to solve grouping problems efficiently.
"What if we used character count arrays as keys instead of sorting? 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 string as key
Sorting letters of each word gives a unique key for all its anagrams.Final Answer:
Use sorted strings as keys to group words with the same letters -> Option BQuick Check:
Sorted word key groups anagrams = A [OK]
- Grouping by word length only
- Using first letter as key
- Counting vowels instead of letters
Solution
Step 1: Identify key and value types
Keys are sorted strings, values are arrays of strings (anagrams).Step 2: Match types in Map initialization
Map matches key as string and value as string array.Final Answer:
const map = new Map(); -> Option AQuick Check:
Map key=string, value=string array = D [OK]
- Using number as key instead of string
- Using number array as value
- Confusing value type with number
function groupAnagrams(strs: string[]): string[][] {
const map = new Map();
for (const str of strs) {
const key = str.split('').sort().join('');
if (!map.has(key)) map.set(key, []);
map.get(key)!.push(str);
}
return Array.from(map.values());
}
console.log(groupAnagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']));Solution
Step 1: Sort each word to create keys
"eat", "tea", "ate" all sort to "aet"; "tan", "nat" to "ant"; "bat" to "abt".Step 2: Group words by keys in map
Map groups: "aet" -> ["eat", "tea", "ate"], "ant" -> ["tan", "nat"], "abt" -> ["bat"].Final Answer:
[["eat", "tea", "ate"], ["tan", "nat"], ["bat"]] -> Option CQuick Check:
Sorted keys group anagrams = B [OK]
- Mixing groups by length or first letter
- Returning individual words instead of groups
- Incorrect grouping order
function groupAnagrams(strs: string[]): string[][] {
const map = new Map();
for (const str of strs) {
const key = str.split('').sort();
if (!map.has(key)) map.set(key, []);
map.get(key)!.push(str);
}
return Array.from(map.values());
}Solution
Step 1: Check key creation
str.split('').sort() returns an array, not a string key.Step 2: Fix key by joining sorted array
Use str.split('').sort().join('') to create string key for map.Final Answer:
The key is an array, should be a string after join() -> Option AQuick Check:
Key must be string, not array = A [OK]
- Using array as map key without joining
- Ignoring map.has() check
- Confusing Map with plain object
['abc', 'bca', 'cab', 'xyz', 'zyx', 'zxy', 'aabb', 'baba'], which code snippet correctly groups anagrams using a hash map and filters out groups with less than 3 words?Solution
Step 1: Create keys by sorting letters
Sorting letters groups anagrams correctly, e.g., "abc", "bca", "cab" all become "abc".Step 2: Filter groups with 3 or more words
Use filter to keep only groups where length >= 3.Final Answer:
Code snippet using sorted keys and filtering groups by length >= 3 -> Option DQuick Check:
Sort keys + filter groups >= 3 = C [OK]
- Using word length or first letter as key
- Reversing letters instead of sorting
- Not filtering groups by size
Ready to prove it?
Pass the test and this pattern moves unknown
