Suppose we have a data structure of employee information, there are employee's unique id, his importance value and his direct subordinates' id. As an example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. And suppose their importance values are 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []].
So, if we have the employee information of a company, and an employee id, we have to find the total importance value of this employee and all his subordinates.
So, if the input is like [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1, then the output will be 11, as Emp1 has importance value 5, and there are two direct subordinates of Emp1, they are − Emp2 and Emp3. Now both have importance value 3. So, the total importance value of Emp1 is 5 + 3 + 3 = 11.
To solve this, we will follow these steps −
- weight := a new map, leader := a new map
- for each e in employees, do
- weight[e[0]] := e[1]
- leader[e[0]] := e[2]
- res := 0
- res := res + weight[id]
- queue := leader[id]
- while queue is non-zero, do
- new_queue := a new list
- node := delete last element from queue
- res := res + weight[node]
- if leader[node] is non-zero, then
- new_queue := new_queue + leader[size of leader]
- queue := queue + new_queue
- return res
Let us see the following implementation to get better understanding −
Example
class Solution(object): def getImportance(self, employees, id): weight = {} leader = {} for e in employees: weight[e[0]] = e[1] leader[e[0]] = e[2] res = 0 res += weight[id] queue = leader[id] while queue: new_queue = [] node = queue.pop() res += weight[node] if leader[node]: new_queue += leader[node] queue += new_queue return res ob = Solution() print(ob.getImportance([[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1))
Input
[[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output
11