Question presented to candidate: "Explain how Dijkstra's algorithm finds shortest paths in a weighted graph, then implement it in Python for a graph given as an edge list. What is its complexity, and when does it give the wrong answer?"
What a strong answer should cover:
- The greedy rule: repeatedly settle the unsettled node with the smallest tentative distance, then relax its outgoing edges.
- Edge relaxation,
distinitialised to infinity except the source, and aparentarray to rebuild the route. - A min-heap of
(distance, node)tuples withheapq, and lazy deletion: push a new entry on every improvement and skip stale entries when popped, becauseheapqhas no decrease-key. - O((V + E) log V) time with a binary heap, O(V + E) space; why non-negative weights are required (and what to use instead).
- Python specifics:
float("inf")for unreachable, tuples compare element by element so ties fall back to the node, and that node must be comparable.
Clarifying questions expected:
- "Can weights be negative, and is the graph directed?"
- "Do you need the route itself, or only the distance? What should unreachable nodes return?"
Code / implementation expected: Yes โ a Python dijkstra(n, edges, source) using heapq, returning distances (and ideally parents for the path).