Skip to content

Commit 1efa9cc

Browse files
authored
Create employee-importance.py
1 parent d2b7846 commit 1efa9cc

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Python/employee-importance.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
# You are given a data structure of employee information,
5+
# which includes the employee's unique id, his importance value and his direct subordinates' id.
6+
#
7+
# For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3.
8+
# They have importance value 15, 10 and 5, respectively.
9+
# Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]],
10+
# and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1,
11+
# the relationship is not direct.
12+
#
13+
# Now given the employee information of a company,
14+
# and an employee id, you need to return the total importance value of this employee and all his subordinates.
15+
#
16+
# Example 1:
17+
# Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
18+
# Output: 11
19+
#
20+
# Explanation:
21+
# Employee 1 has importance value 5, and he has two direct subordinates:
22+
# employee 2 and employee 3. They both have importance value 3.
23+
# So the total importance value of employee 1 is 5 + 3 + 3 = 11.
24+
#
25+
# Note:
26+
# One employee has at most one direct leader and may have several subordinates.
27+
# The maximum number of employees won't exceed 2000.
28+
29+
"""
30+
# Employee info
31+
class Employee(object):
32+
def __init__(self, id, importance, subordinates):
33+
# It's the unique id of each node.
34+
# unique id of this employee
35+
self.id = id
36+
# the importance value of this employee
37+
self.importance = importance
38+
# the id of direct subordinates
39+
self.subordinates = subordinates
40+
"""
41+
class Solution(object):
42+
def getImportance(self, employees, id):
43+
"""
44+
:type employees: Employee
45+
:type id: int
46+
:rtype: int
47+
"""
48+
if employees[id-1] is None:
49+
return 0
50+
result = employees[id-1].importance
51+
for id in employees[id-1].subordinates:
52+
result += self.getImportance(employees, id)
53+
return result
54+
55+
56+
# Time: O(n)
57+
# Space: O(w), w is the max number of nodes in the levels of the tree
58+
class Solution2(object):
59+
def getImportance(self, employees, id):
60+
"""
61+
:type employees: Employee
62+
:type id: int
63+
:rtype: int
64+
"""
65+
result, q = 0, collections.deque([id])
66+
while q:
67+
curr = q.popleft()
68+
employee = employees[curr-1]
69+
result += employee.importance;
70+
for id in employee.subordinates:
71+
q.append(id)
72+
return result

0 commit comments

Comments
 (0)