PythonStudio
Interview Problems

Dijkstra Shortest Paths

medium · dijkstra

Given n >= 1 vertices numbered 0..n-1, directed edges [source,destination,weight] with nonnegative integer weights, and a valid source, return a length-n distance list. Use None for unreachable vertices; source has distance 0. Parallel edges, self-loops and zero weights are allowed. Edges are directed, not automatically bidirectional. At most 100 vertices and 1000 edges. Examples (JSON; null means Python None): Input: {"n": 4, "edges": [[0, 1, 4], [0, 2, 1], [2, 1, 1], [1, 3, 2]], "source": 0} Output: [0, 2, 1, 4] Input: {"n": 3, "edges": [[0, 1, 0]], "source": 0} Output: [0, 0, null]

Starter code

def shortest_paths(n: int, edges: list[list[int]], source: int) -> list[int | None]:
    """Return nonnegative weighted shortest distances, including unreachable nodes."""
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python compiler