FastPrepDirect Manager and Peer Queries

Direct Manager and Peer Queries

Google logoGoogle● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

There are personCount people numbered from 0 through personCount - 1. Process a chronological list of relationship operations.

  • [0, a, b] records that person a is the direct manager of person b.
  • [1, a, b] records that persons a and b are peers, meaning they have the same direct manager.
  • [2, a, b] asks whether the facts recorded so far prove that person a is the direct manager of person b.

All update operations are mutually consistent. A query whose manager is not yet known returns false.

Return the answers to all type-2 operations in their original order.

Function

answerManagerQueries(personCount: int, operations: int[][]) → boolean[]

Examples

Example 1

personCount = 5operations = [[0,0,1],[1,1,2],[2,0,2],[2,3,2]]return = [true,false]

Person 0 manages person 1. Because 1 and 2 are peers, person 0 also manages person 2. Person 3 is not their manager.

Example 2

personCount = 3operations = [[2,0,1],[0,0,1],[2,0,1],[1,1,2],[2,0,2]]return = [false,true,true]

The first query is false because person 1's manager is still unknown. The manager assertion answers the second query, and the later peer assertion propagates that manager to person 2.

Example 3

personCount = 5operations = [[1,1,2],[0,4,2],[2,4,1],[0,0,3],[2,4,3]]return = [true,false]

Peers 1 and 2 share manager 4. Person 3 instead has manager 0, so the final query is false.

Constraints

  • 1 <= personCount <= 100000.
  • 1 <= operations.length <= 100000.
  • Every operation has exactly three integers [type, a, b].
  • 0 <= type <= 2 and 0 <= a, b < personCount.
  • Type-0 and type-1 operations never contradict facts recorded earlier.
  • At least one operation is a query.

More Google problems

See Google hiring insights
public boolean[] answerManagerQueries(int personCount, int[][] operations) {
    // write your code here
}
personCount5
operations[[0,0,1],[1,1,2],[2,0,2],[2,3,2]]
expected[true,false]
Checking account…