Hierarchy Tree

You are given n employees. Each employee has at most one direct boss.

The array p represents the management hierarchy: p[i] = boss of employee i , p[i] = -1 β†’ no boss (top-level)

This forms a forest of trees (multiple hierarchies).

You task is to divide employees into groups such that: No employee is in the same group as their boss

Example 1:

Input: n = 5 , p = [-1, 1, 2, 1, -1]

Output: 3

Explanation:

Tree structure:

1
└── 2
    └── 3

1
└── 4

5

Longest chain: 1 β†’ 2 β†’ 3

Length = 3

So minimum groups required = 3

Example 2:

Input: n = 4 , parent = [-1, -1, -1, -1]

Output: 1

Explanation :

All employees are independent.

No hierarchy β†’ all can be in same group.

Now Your Turn!

Pick the correct output for the given input

Input : n = 6 , parent = [-1,1,-1,3,-1,5]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≀ n ≀ 2000
  • p[i] ∈ [-1, 1..n]

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int minGroups(int n, vector<int>& p) {
// Write your code here
return 0;
}
};
Test Case

Input:

P