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 - Hash Map Approach INPUT Employee Hierarchy Tree ID: 1 Imp: 5 ID: 2 Imp: 3 ID: 3 Imp: 3 Input Data: employees = [[1,5,[2,3]], [2,3,[]],[3,3,[]]] id = 1 Format: [id, importance, [subs]] Manager (target) Subordinates ALGORITHM STEPS 1 Build Hash Map Map ID to employee object hashMap = { 1: {id:1, imp:5, subs:[2,3]} 2: {id:2, imp:3}, 3: {id:3...} 2 Start with Target Get employee with id=1 3 BFS/DFS Traversal Visit all subordinates Queue: [1] --> [2,3] --> [] Visit 1: total = 0 + 5 = 5 Visit 2: total = 5 + 3 = 8 Visit 3: total = 8 + 3 = 11 4 Return Total Sum of all importance values FINAL RESULT Aggregated Importance ID: 1 Imp: 5 [OK] ID: 2 +3 ID: 3 +3 Calculation: 5 + 3 + 3 = 11 OUTPUT 11 Key Insight: Using a Hash Map enables O(1) employee lookup by ID, avoiding repeated array scans. BFS/DFS traversal from target employee collects all subordinate importance values efficiently. Time Complexity: O(n) | Space Complexity: O(n) where n = number of employees TutorialsPoint - Employee Importance | Hash Map Approach
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