Count Employees Under Each Manager
You are given a company with n employees, labeled from 1 to n.
Employee 1 is the CEO. For every employee from 2 to n, you are given their direct manager in the array manager, where manager[i - 2] is the direct manager of employee i.
For each employee, find how many employees work under them, directly or indirectly.
Return an array of size n, where answer[i - 1] represents the number of subordinates of employee i.
Example 1:
Input: n = 5, manager = [1, 1, 2, 3]
Output: [4, 1, 1, 0, 0]
Explanation:
- Employee 1 manages employees 2 and 3, and indirectly also manages 4 and 5. So they have 4 subordinates.
- Employee 2 manages employee 4, so they have 1 subordinate.
- Employee 3 manages employee 5, so they also have 1 subordinate.
- Employees 4 and 5 do not manage anyone.
Example 2:
Input: n = 7, manager = [1, 1, 2, 2, 4, 4]
Output: [6, 4, 0, 2, 0, 0, 0]
Explanation:
The company hierarchy is:
- 1 manages 2 and 3
- 2 manages 4 and 5
- 4 manages 6 and 7
So:
- Employee 1 has 6 subordinates.
- Employee 2 has 4 subordinates: 4, 5, 6, 7
- Employee 3 has 0 subordinates.
- Employee 4 has 2 subordinates: 6, 7
- Employees 5, 6, 7 have 0 subordinates.
Now Your Turn!
Pick the correct output for the given inputInput: n = 4, manager = [1, 2, 2]
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 ≤ 2 × 105
- manager.length == n - 1
- 1 ≤ manager[i] ≤ n
- Employee 1 is the CEO
- The given hierarchy forms a valid company structure