Space
Open
From Fieldwork
Scales
Archive
First, convert the list of employees into a Hash Map (Dictionary). This allows us to look up an employee by their ID in O(1) time, preventing the O(N) search overhead during the traversal.
class Solution:
def getImportance(self, employees: List['Employee'], id: int) -> int:
# 1. Create a hash map for O(1) lookup: {id -> Employee Object}
emap = {e.id: e for e in employees}
# 2. Define a helper function for Depth First Search
def dfs(eid):
employee = emap[eid]
# Return current importance + sum of subordinates' importance
return employee.importance + sum(dfs(sub_id) for sub_id in employee.subordinates)
# 3. Kick off the recursion
return dfs(id)Practice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode