Group values by a key07.01
Grouping is key → list of items with that key. First time you see the key, put an empty list (or a one-item list). Later items append. The key is unique. The list grows.
Typical: anagram buckets (sorted letters → words), rows by id, remainder → numbers. The map's values are collections, not scalars.
Same skill, three traces. Read all three before you try it.
01by parity - given
a = [4, 1, 9, 2]- walk
even →
[4,2]odd →
[1,9]- result
{0:[4,2], 1:[1,9]}if key isx%2
02all one group - given
a = [2, 8, 4]- walk
all even
- result
{0:[2,8,4]}
03empty - given
a = []- walk
no groups
- result
{}
groupBy(a, keyFn).a is an array of integers. keyFn is a function that takes one value and returns a key.Append each value onto the list for
keyFn(value). Return the map of lists.a = [4, 1, 9, 2] → {0:[4,2], 1:[1,9]} if key is x%2.a = [2, 8, 4] → {0:[2,8,4]}.a = [] → {}.constraintsa is a list of integers and may be empty. keyFn is a function from a value to a key. In this drill keyFn is x%2.
- Group Anagrams0/3 skills ready · hash maps · mediumopen
- Group Anagrams0/3 skills ready · hash maps · mediumopen
Every Check with Awel is frozen here. Open one to read the code or load it back into the editor.