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.
1using System.Collections.Generic;
2
3class Employee {
4 public int id;
5 public int importance;
6 public IList<int> subordinates;
7}
8
9class Solution {
10 public int GetImportance(IList<Employee> employees, int id) {
11 var employeeMap = new Dictionary<int, Employee>();
12 foreach (var e in employees) {
13 employeeMap[e.id] = e;
14 }
15 return DFS(employeeMap, id);
16 }
17
18 private int DFS(Dictionary<int, Employee> map, int id) {
19 var employee = map[id];
20 int totalImportance = employee.importance;
21 foreach (var subId in employee.subordinates) {
22 totalImportance += DFS(map, subId);
23 }
24 return totalImportance;
25 }
26}
This C# solution involves a dictionary for mapping employees and a recursive DFS function to compute total importance by adding the subordinate importance recursively.
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.