FastPrepAggregate Machine Topology

Aggregate Machine Topology

OpenAI logoOpenAI● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

A cluster snapshot contains one report from every machine. For each index i, machineIds[i] is a unique machine ID and parentIds[i] is the parent machine's ID. Exactly one machine has parent -1; it is the root. The remaining parent relationships form one rooted tree.

Return a canonical topology summary. Each output row is [machineId, parentId, depth, subtreeSize], where depth counts edges from the root and subtreeSize counts the machine itself and every descendant.

Rows must use preorder traversal. When a machine has multiple children, visit them in increasing machine-ID order. The root row therefore exposes the total machine count in its subtreeSize field.

Function

aggregateMachineTopology(machineIds: int[], parentIds: int[]) → int[][]

Examples

Example 1

machineIds = [30,10,20]parentIds = [10,-1,10]return = [[10,-1,0,3],[20,10,1,1],[30,10,1,1]]

Machine 10 is the root. Its children are visited as 20 and then 30. The root subtree contains all three machines.

Example 2

machineIds = [7,2,9,1,5,3]parentIds = [3,1,3,-1,2,1]return = [[1,-1,0,6],[2,1,1,2],[5,2,2,1],[3,1,1,3],[7,3,2,1],[9,3,2,1]]

The root has children 2 and 3. Machine 2 owns a two-machine subtree, while machine 3 owns a three-machine subtree. Preorder visits each parent's increasing-ID children before returning to later siblings.

Constraints

  • 1 <= machineIds.length == parentIds.length <= 100000.
  • Every machine ID is unique and lies in [0, 10^9].
  • Exactly one value in parentIds is -1.
  • Every other parent ID occurs in machineIds, and all parent relationships form one rooted tree.
  • The output rows use deterministic preorder with children sorted by increasing machine ID.

More OpenAI problems

See OpenAI hiring insights
public int[][] aggregateMachineTopology(int[] machineIds, int[] parentIds) {
    // Write your code here.
}
machineIds[30,10,20]
parentIds[10,-1,10]
expected[[10,-1,0,3],[20,10,1,1],[30,10,1,1]]
Checking account…