Went with Dijkstra pretty quickly, which was the right call, but I fumbled the unreachable node check at first.
Recognize this as the classic single-source shortest path problem on a weighted directed graph with non-negative weights, so Dijkstra's algorithm is optimal. Use a min-heap to efficiently extract the next closest node, relax edges, and track distances. After computing distances, check for unreachable nodes (distance = infinity) and return -1 if any exist; otherwise return the maximum distance as the total time.
Pro tip: Clarify edge weight constraints upfront—if negative weights are possible, Dijkstra fails and Bellman-Ford is needed. Mentioning this shows you consider edge cases and algorithm applicability, which interviewers value.
Ask about edge weights (non-negative?), graph size, and whether the graph is connected. Confirm that the goal is to find shortest distances from one source to all nodes and return the maximum of those distances, or -1 if any node is unreachable.
For non-negative weights, Dijkstra's algorithm with a min-heap is optimal (O((V+E) log V)). If negative weights are allowed, use Bellman-Ford (O(VE)) and handle negative cycles.
Initialize distances to infinity, set source distance to 0, and push source into a min-heap. While the heap is not empty, pop the node with the smallest distance, skip if already processed, and relax all outgoing edges, updating distances and pushing improved nodes.
After the algorithm, scan all distances. If any node (except possibly the source) has distance infinity, return -1. Otherwise, return the maximum distance, which represents the time for all nodes to receive the signal.
State time complexity O((V+E) log V) and space O(V+E). Walk through a small example, including a disconnected case, to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.