Space
Open
From Fieldwork
Scales
Archive
Adjacency lists are used because we're trying to represent a sparse graph. Data and goals and constraints inform structure.
class Solution:
from collections import deque
def numOfMinutes(self, n, headID, manager, informTime):
# 1. Build Adjacency List (Manager -> subordinates)
adj = [[] for _ in range(n)]
for employee_id, mgr_id in enumerate(manager):
if mgr_id != -1:
adj[mgr_id].append(employee_id)
# 2. BFS: (current_employee, cumulative_time_to_reach_them)
queue = deque([(headID, 0)])
max_time = 0
while queue:
curr_emp, curr_time = queue.popleft()
# Update the total time needed
max_time = max(max_time, curr_time)
# For every subordinate, the time to reach them is
# current time + the time this manager takes to inform everyone
for subordinate in adj[curr_emp]:
queue.append((subordinate, curr_time + informTime[curr_emp]))
return max_timePractice 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