FastPrepGroup Names by Department

Group Names by Department

Mastercard logoMastercard● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given a matrix people. Each row contains exactly two strings:

  • people[i][0] is a person's name.
  • people[i][1] is that person's department.

Group the names by department.

Return a matrix in which each row begins with a department, followed by the names assigned to it. Order department rows by each department's first appearance in people, and preserve input order among names in the same department.

Function

groupNamesByDepartment(people: String[][]) → String[][]

Examples

Example 1

people = [["Ava","Data"],["Ben","Risk"],["Chen","Data"],["Diya","Risk"]]return = [["Data","Ava","Chen"],["Risk","Ben","Diya"]]

Data appears first, followed by Risk. Names remain in their original order within each department.

Example 2

people = [["Mina","Finance"],["Noah","Engineering"],["Omar","Finance"]]return = [["Finance","Mina","Omar"],["Engineering","Noah"]]

The Finance row is first because that department is encountered first.

Example 3

people = [["Zoe","Legal"]]return = [["Legal","Zoe"]]

A single record creates one department row.

Constraints

  • 1 <= people.length <= 10^5.
  • people[i].length = 2.
  • Every name and department is non-empty.
  • The total number of characters in people is at most 10^6.

More Mastercard problems

See Mastercard hiring insights
public String[][] groupNamesByDepartment(String[][] people) {
  // Write your code here.
}
people[["Ava","Data"],["Ben","Risk"],["Chen","Data"],["Diya","Risk"]]
expected[["Data", "Ava", "Chen"], ["Risk", "Ben", "Diya"]]
Checking account…