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

Distances between every pair of nodes

Medium · Target 15 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; the same pair may appear more than once. Return an n × n matrix whose entry [i][j] is the length of the shortest path from i to j, or −1 if there is none. The diagonal is 0.

Examples

InputOutputWhy
n = 2, edges = [[0,1,5]][[0,5],[-1,0]]Node 1 cannot reach node 0.
n = 3, edges = [[0,1,9],[0,1,4],[1,2,0]][[0,4,4],[-1,0,0],[-1,-1,0]]The lighter of two parallel edges counts; zero weights are allowed.
n = 4, edges = [[0,1,3],[1,2,1],[0,2,7],[2,3,2],[3,0,1],[3,1,6]][[0,3,4,6],[4,0,1,3],[3,6,0,2],[1,4,5,0]]The figure in the lesson.

Constraints

  • 1 ≤ n ≤ 150
  • 0 ≤ edges.length ≤ n(n − 1)
  • 0 ≤ w ≤ 10⁴

Hints

Hint 1

Start from a matrix holding the direct edge weights (the smallest, if an edge repeats), 0 on the diagonal and infinity elsewhere.

Hint 2

For each node k in turn, allow paths to pass through k: d[i][j] = min(d[i][j], d[i][k] + d[k][j]).

Hint 3

k must be the outermost loop. Convert infinity to −1 only at the end.

Where people lose marks

  • Putting the k loop inside the i and j loops.
  • Overwriting a parallel edge with a heavier one instead of keeping the minimum.
  • Adding two infinities, which overflows in fixed-width integers.
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.