What is Floyd-Warshall algorithm?
Why Interviewers Ask This
This question targets practical, hands-on experience with Data Structures & Algorithms. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
Floyd-Warshall finds shortest paths between all pairs of vertices in a weighted graph (positive or negative weights, but no negative cycles). Algorithm: dp[i][j][k] = shortest path from i to j using only vertices {1..k} as intermediate nodes. Key insight: either vertex k is on the shortest path from i to j (so use k as intermediate), or it's not (path through vertices 1..k-1). Recurrence: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]). Triple nested loop: for each intermediate vertex k, for each source i, for each destination j, update dist[i][j]. Initialize: dist[i][i] = 0; dist[i][j] = edge weight if edge exists, else ∞. Time: O(V³). Space: O(V²) — the 2D distance matrix (optimize by using k in-place). Negative cycle detection: if dist[i][i] < 0 after running, vertex i is on a negative cycle. Applications: (1) All-pairs shortest path in dense graphs; (2) Transitive closure of a graph (reachability); (3) Finding the diameter of a graph (max shortest path); (4) Inversion of real matrices. Comparison: for all-pairs in sparse graphs, run Dijkstra from every vertex: O(V × (V+E) log V); for dense graphs Floyd-Warshall O(V³) may be comparable and simpler.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last Data Structures & Algorithms project, I used this when...' immediately makes your answer more credible and memorable.