Sponsored
Sponsored
The problem can be approached by using a Depth-First Search (DFS). The main idea is to accumulate the importance of an employee and all of their direct and indirect subordinates. We use a recursive function to traverse the subordinates of each employee. The base case is when an employee has no subordinates (leaf node). Each recursion step accumulates importance from the current employee and proceeds to accumulate from its subordinates.
Time Complexity: O(N), where N is the number of employees, as each employee is visited once.
Space Complexity: O(N), due to the recursion stack and storage in the map for employees.
1#include <vector>
2#include <unordered_map>
3using namespace std;
4
5struct Employee {
6 int id;
7 int importance;
8 vector<int> subordinates;
9};
10
11class Solution {
12public:
13 int getImportance(vector<Employee*> employees, int id) {
14 unordered_map<int, Employee*> employee_map;
15 for (auto e : employees) {
16 employee_map[e->id] = e;
17 }
18
19 return dfs(employee_map, id);
20 }
21
22private:
23 int dfs(unordered_map<int, Employee*>& map, int id) {
24 Employee* employee = map[id];
25 int total_importance = employee->importance;
26 for (int sub_id : employee->subordinates) {
27 total_importance += dfs(map, sub_id);
28 }
29 return total_importance;
30 }
31};
This C++ solution uses a DFS approach recursively. It builds a mapping from employee ids to Employee objects for O(1) access and uses a helper function dfs
to calculate the importance by summing up the values of direct and indirect subordinates.
An alternative method involves using Breadth-First Search (BFS). In this approach, a queue is used to iteratively explore each level of employee hierarchy starting from the given employee ID. One processes each employee by summing their importance and enqueuing their subordinates. This technique assures visiting all employees in a breadth-wise manner and eventually collecting the cumulative importance value.
Time Complexity: O(N), as it processes each employee once.
Space Complexity: O(N), due to the queue and employee mapping storage.
1class
This Python code uses a BFS approach. We employ a queue where we enqueue employees as we visit them and total their importance. Every dequeued employee adds their importance to the result and their subordinates to the queue.