Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

A Floyd–Warshall implementation writes its loops as for i … for j … for k (k innermost) instead of k outermost, and runs the triple loop once. What happens in general?

  1. A. It still gives correct results, only slower
  2. B. It still gives correct results because min() is commutative
  3. C. It always returns the correct result but may report false negative cycles
  4. D. Some distances can stay larger than the true shortest paths, because dist[i][k] or dist[k][j] may be used before it has been finalised

Correct answer: D. Some distances can stay larger than the true shortest paths, because dist[i][k] or dist[k][j] may be used before it has been finalised

Correctness relies on the invariant that after phase k all paths using intermediates {0..k} are known; with k innermost, dist[i][j] is fixed using possibly unimproved dist[i][k] and dist[k][j]. Running the wrong-order loop repeatedly (up to 3 times) does converge, but a single pass is not guaranteed correct.

More Coding Interview Problems questions

Exams that ask this topic