Skip to the solution
HardDSA12 min read

How does the Floyd-Warshall algorithm work?

897 views

The problem

Question presented to candidate: "Explain the Floyd-Warshall algorithm. Implement it in Python for a directed weighted graph with V nodes, return the matrix of shortest distances between every pair, and tell me how you would detect a negative cycle."

What a strong answer should cover:

  • The DP idea: after processing k, dist[i][j] is the shortest path using only nodes 0..k as intermediates; the recurrence dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]).
  • The loop order: k must be the outermost loop, and why updating one matrix in place is safe.
  • O(V³) time and O(V²) space; when it beats running Dijkstra from every node (small or dense graphs, negative weights).
  • Negative weights are fine; a negative cycle shows up as dist[i][i] < 0; a next matrix rebuilds routes.
  • Python specifics: float("inf") for missing edges, building the matrix with a list comprehension (not [[INF] * n] * n, which aliases rows), and pure-Python triple loops being slow for large V.

Clarifying questions expected:

  • "How many nodes? Are negative weights or negative cycles possible?"
  • "Do you need the routes, or only the distances?"

Code / implementation expected: Yes — a Python floyd_warshall(n, edges) returning the distance matrix, ideally plus a next matrix for route reconstruction.

  • dsa
  • graph
  • shortest-path
  • dynamic-programming

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read · 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonAll-pairs distances and route rebuilding
PythonLoop order, negative edges and negative cycles

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 134 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

How do you serialize and deserialize a binary tree?

Continue