The Group the People Given the Group Size They Belong To coding problem gives you an array groupSizes where groupSizes[i] represents the exact size of the group that person i must be in. You need to return a list of groups such that every person is in a group of their required size. The problem guarantees that a valid grouping always exists.
Meta and Amazon ask this Hash Table and Greedy interview pattern to test your ability to organize data based on constraints. It’s a "Medium" problem that evaluates whether you can use a dictionary/map to accumulate items until a condition (group size) is met, and then "flush" them to a result list. It checks your understanding of dynamic grouping.
The problem uses a Hash Map with a Greedy "Flush".
groupSize and the value is a list of people (IDs) who belong to a group of that size.i with size s, append i to map[s].map[s].length == s. If the list has reached the required capacity, the group is "full."s to catch future people with the same size requirement.groupSizes = [3, 3, 3, 3, 3, 1, 3]
map[3] = [0].map[3] = [0, 1].map[3] = [0, 1, 2]. Full! Add to result, reset map[3] = [].map[3] = [3].map[3] = [3, 4].map[1] = [5]. Full! Add to result, reset map[1] = [].map[3] = [3, 4, 6]. Full! Add to result.
Result: [[0, 1, 2], [5], [3, 4, 6]].map[3] = [0, 1, 2, 3, 4, 6]) and then writing a second loop to chunk them into sizes of 3. Flushing during the initial iteration is cleaner and saves memory.Whenever you need to chunk items into fixed sizes based on a shared property, the "Append and Flush" pattern using a Hash Map is the most efficient and readable solution.