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.
1import java.util.*;
2
3class Employee {
4 public int id;
5 public int importance;
6 public List<Integer> subordinates;
7}
8
9class Solution {
10 public int getImportance(List<Employee> employees, int id) {
11 Map<Integer, Employee> employeeMap = new HashMap<>();
12 for (Employee e : employees) {
13 employeeMap.put(e.id, e);
14 }
15 return dfs(employeeMap, id);
16 }
17
18 private int dfs(Map<Integer, Employee> map, int id) {
19 Employee employee = map.get(id);
20 int total_importance = employee.importance;
21 for (int sub_id : employee.subordinates) {
22 total_importance += dfs(map, sub_id);
23 }
24 return total_importance;
25 }
26}
This Java solution creates a map for O(1) lookups and employs a DFS recursive helper method. It accumulates importance recursively, similar to the approaches in Python and C++.
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.
1import
In this Java version, BFS is utilized using a queue structure. The code follows a similar pattern of summing the importance of dequeued employees and adding their subordinates into the queue.