FastPrepSelected Tree Nodes at the Same Level and Height

Selected Tree Nodes at the Same Level and Height

Microsoft logoMicrosoft● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

A rooted tree contains nodes numbered from 0 through n - 1. The array parent describes the tree: parent[0] = -1, and every other entry gives that node's parent.

Given distinct selected node numbers, return two booleans: whether all selected nodes have the same depth from the root, and whether all selected nodes have the same height. A leaf has height 0; another node's height is one plus the maximum height of any child.

Function

sameLevelAndHeight(parent: int[], selected: int[]) → boolean[]

Examples

Example 1

parent = [-1,0,0,1,1,2]selected = [3,4,5]return = [true,true]

All three nodes are leaves at depth 2, so they share both depth and height.

Example 2

parent = [-1,0,0,1,3,2]selected = [1,2]return = [true,false]

Nodes 1 and 2 share depth 1, but their heights are 2 and 1.

Constraints

  • 1 <= parent.length <= 100000
  • parent[0] = -1
  • For 1 <= i < parent.length, 0 <= parent[i] < i
  • 1 <= selected.length <= parent.length
  • Selected node numbers are distinct and valid

More Microsoft problems

See Microsoft hiring insights
public boolean[] sameLevelAndHeight(int[] parent, int[] selected) {
  // Write your code here.
}
parent[-1,0,0,1,1,2]
selected[3,4,5]
expected[true,true]
Checking account…