FastPrepFind Root of N-Ary Tree

Find Root of N-Ary Tree

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

An N-ary tree has one node for every distinct integer in values. Each pair [parent, child] in edges is a directed tree edge from a node to one of its children.

The edges form exactly one valid rooted tree over all labels in values. Return the label of its root.

Function

findRoot(values: int[], edges: int[][]) → int

Examples

Example 1

values = [1,2,3,4,5,6]edges = [[1,3],[1,2],[1,4],[3,5],[3,6]]return = 1

Every label except 1 appears as a child, so 1 is the root.

Example 2

values = [7]edges = []return = 7

A one-node tree has no edges, and its only label is the root.

Example 3

values = [5,1,9,4]edges = [[9,5],[9,1],[1,4]]return = 9

The child labels are 5, 1, and 4. The remaining label 9 is the root.

Constraints

  • 1 <= values.length <= 100000.
  • All labels in values are distinct integers between -10^9 and 10^9.
  • edges.length == values.length - 1.
  • Every edge contains two labels from values.
  • Every non-root label appears exactly once as a child, and the edges form one valid N-ary tree.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int findRoot(int[] values, int[][] edges) {
    // Write your code here.
}
values[1,2,3,4,5,6]
edges[[1,3],[1,2],[1,4],[3,5],[3,6]]
expected1
Checking account…