Problem · Graph

Employee Hierarchy Cycle and Depth Analysis

Learn this problem
MediumMicrosoft logoMicrosoftFULLTIMEPHONE SCREEN
See Microsoft hiring insights

Problem statement

An organization has n employees labeled from 0 to n - 1. The array manager describes the direct manager relation:

  • manager[i] = -1 means employee i is the root of the organization.
  • Otherwise, manager[i] is the employee who directly manages employee i.

Exactly one employee has manager -1. Every other entry is a valid employee index. The reported relations may still contain a directed cycle disconnected from the root.

Return a two-element array:

  • If any management cycle exists, return [1, -1].
  • Otherwise, return [0, maxDepth], where an employee's depth is the number of manager edges from the root to that employee and maxDepth is the greatest employee depth.

Function

analyzeHierarchy(manager: int[]) → int[]

Examples

Example 1

manager = [-1,0,0,1,1,3]return = [0,3]

No cycle exists. Employee 5 is reached along 0 -> 1 -> 3 -> 5, so the maximum depth is 3.

Example 2

manager = [1,2,0,-1]return = [1,-1]

Employees 0, 1, and 2 form the management cycle 0 -> 1 -> 2 -> 0.

Example 3

manager = [-1]return = [0,0]

The only employee is the root, whose depth is 0.

Constraints

  • 1 <= manager.length <= 2 * 10^5
  • Exactly one entry of manager is -1.
  • Every other entry is an employee index in [0, manager.length - 1].

More Microsoft problems

drafts saved locally
public int[] analyzeHierarchy(int[] manager) {
    // Write your code here.
}
manager[-1,0,0,1,1,3]
expected[0,3]
checking account