Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Shortest distances from one node

Medium · Target 20 minutes · Graphs

A directed graph has n nodes numbered 0 to n − 1. Each triple [u, v, w] in edges is an edge from u to v with non-negative weight w; there may be several edges between the same two nodes. Return a list whose entry v is the smallest total weight of a path from src to v, or −1 if v cannot be reached. The entry for src is 0.

Examples

InputOutputWhy
n = 3, edges = [[0,1,5]], src = 0[0, 5, -1]Node 2 has no incoming edge.
n = 4, edges = [[0,1,1],[1,2,1],[0,2,5],[2,3,0]], src = 0[0, 1, 2, 2]Two light edges beat one heavy one; a zero-weight edge is allowed.
n = 4, edges = [[0,1,4],[0,1,1],[1,3,2]], src = 0[0, 1, -1, 3]Parallel edges: the lighter one counts.

Constraints

  • 1 ≤ n ≤ 10⁴
  • 0 ≤ edges.length ≤ 5 · 10⁴
  • 0 ≤ w ≤ 10⁴

Hints

Hint 1

Build an adjacency list of (neighbour, weight) pairs.

Hint 2

Keep a min-heap of (distance, node). The first time a node is popped, its distance is final.

Hint 3

When a node is popped a second time, the entry is stale: skip it.

Where people lose marks

  • Settling a node when it is pushed rather than when it is popped: a cheaper route may still arrive.
  • Not skipping stale entries, which re-relaxes edges with an outdated distance (wrong in some implementations, slow in all).
  • Using Dijkstra on a graph with a negative weight. Use Bellman–Ford.
  • Initialising distances with a sentinel that overflows when a weight is added to it.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.