Problem · Array

Nickname-Constrained Grouping

Learn this problem
MediumZoox logoZooxFULLTIMEONSITE INTERVIEW

Problem 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:

  1. Number the g = names.length / k groups from 0 through g - 1, and set a group cursor to 0.
  2. Process distinct nicknames in lexicographically increasing order.
  3. For one nickname, order its people by name and then by original index.
  4. If this nickname has f people, assign person j in that order to group (cursor + j) % g, then advance the cursor to (cursor + f) % g.
  5. 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 <= 2000
  • 1 <= k <= names.length
  • names.length is divisible by k.
  • Every name and nickname contains between 1 and 20 lowercase English letters.
  • Each nickname occurs at most min(k, names.length / k) times.

More Zoox problems

drafts saved locally
public int[][] groupPeople(String[] names, String[] nicknames, int k) {
    // Write your code here.
}
names["ana","ben","cara","drew","eli","faye"]
nicknames["red","blue","red","green","blue","green"]
k2
expected[[1,5],[0,4],[2,3]]
checking account