Nickname-Constrained Grouping
Learn this problemProblem statement
You are given parallel arrays names and nicknames. Person i has name names[i], nickname nicknames[i], and original index i. Partition every person into groups of exactly k people so that no group contains the same nickname twice.
The input is guaranteed to admit the following canonical construction:
- Number the
g = names.length / kgroups from0throughg - 1, and set a group cursor to0. - Process distinct nicknames in lexicographically increasing order.
- For one nickname, order its people by name and then by original index.
- If this nickname has
fpeople, assign personjin that order to group(cursor + j) % g, then advance the cursor to(cursor + f) % g. - Sort the original indices inside every group increasingly.
Return the groups in group-number order as an array of index arrays.
Function
groupPeople(names: String[], nicknames: String[], k: int) → int[][]Examples
Example 1
names = ["ana","ben","cara","drew","eli","faye"]nicknames = ["red","blue","red","green","blue","green"]k = 2return = [[1,5],[0,4],[2,3]]Nicknames are processed as blue, green, then red. Cyclic assignment gives group 0 indices [1,5], group 1 indices [0,4], and group 2 indices [2,3]. Every group has size 2 and distinct nicknames.
Example 2
names = ["zoe","amy","kai","bo"]nicknames = ["x","x","y","z"]k = 2return = [[1,2],[0,3]]Within nickname x, index 1 comes before index 0 because amy is lexicographically smaller than zoe. The two occurrences go to different groups before nicknames y and z complete them.
Example 3
names = ["c","a","b"]nicknames = ["z","x","y"]k = 1return = [[1],[2],[0]]Each group has one person. Processing nicknames x, y, and z assigns original indices 1, 2, and 0 to groups 0, 1, and 2.
Constraints
1 <= names.length = nicknames.length <= 20001 <= k <= names.lengthnames.lengthis divisible byk.- Every name and nickname contains between
1and20lowercase English letters. - Each nickname occurs at most
min(k, names.length / k)times.