You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.

You are given an array of employees employees where:

  • employees[i].id is the ID of the ith employee
  • employees[i].importance is the importance value of the ith employee
  • employees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee

Given an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates.

Input & Output

Example 1 — Basic Hierarchy
$ Input: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1
Output: 11
💡 Note: Employee 1 has importance 5, and has two direct subordinates 2 and 3. Employee 2 has importance 3, employee 3 has importance 3. Total: 5 + 3 + 3 = 11.
Example 2 — Single Employee
$ Input: employees = [[1,2,[5]],[5,1,[]]], id = 5
Output: 1
💡 Note: Employee 5 has importance 1 and no subordinates. Total importance is just 1.
Example 3 — Deep Hierarchy
$ Input: employees = [[1,5,[2]],[2,3,[3]],[3,4,[]]], id = 1
Output: 12
💡 Note: Employee 1 has subordinate 2, employee 2 has subordinate 3. Total: 5 + 3 + 4 = 12.

Constraints

  • 1 ≤ employees.length ≤ 2000
  • 1 ≤ employees[i].id ≤ 2000
  • 0 ≤ employees[i].importance ≤ 1000
  • One employee has at most one direct leader and may have several subordinates
  • The IDs in employees[i].subordinates are valid IDs

Visualization

Tap to expand
Employee Importance: Tree TraversalInput Data:[1,5,[2,3]][2,3,[]][3,3,[]]Employee Hierarchy:ID: 1Imp: 5ID: 2Imp: 3ID: 3Imp: 3Traverse from ID=1: 5 + 3 + 3 = 11Algorithm:1. Build hash map2. DFS/BFS from target3. Sum all importanceOutput: 11
Understanding the Visualization
1
Input
Employee array with ID, importance, and subordinate relationships
2
Process
Traverse hierarchy from given employee ID downward
3
Output
Sum of importance values for employee and all subordinates
Key Takeaway
🎯 Key Insight: Use hash map for O(1) employee lookup and tree traversal (DFS/BFS) to visit all subordinates
Asked in
Google 12 Amazon 8 Microsoft 5 Facebook 4
38.6K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen