Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Floyd Warshall All Pairs Shortest Path in DSA Javascript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Floyd Warshall Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Floyd Warshall on a simple graph
What is the output distance matrix after running Floyd Warshall on this graph?
DSA Javascript
const INF = 99999;
const graph = [
  [0, 3, INF, 7],
  [8, 0, 2, INF],
  [5, INF, 0, 1],
  [2, INF, INF, 0]
];

function floydWarshall(graph) {
  const dist = graph.map(row => row.slice());
  const V = graph.length;
  for (let k = 0; k < V; k++) {
    for (let i = 0; i < V; i++) {
      for (let j = 0; j < V; j++) {
        if (dist[i][k] + dist[k][j] < dist[i][j]) {
          dist[i][j] = dist[i][k] + dist[k][j];
        }
      }
    }
  }
  return dist;
}

console.log(floydWarshall(graph));
A[[0, 3, 5, 6],[8, 0, 2, 3],[5, 8, 0, 1],[2, 5, 7, 0]]
B[[0, 3, 5, 6],[7, 0, 2, 3],[3, 6, 0, 1],[2, 5, 7, 0]]
C[[0, 3, 5, 7],[8, 0, 2, 3],[5, 8, 0, 1],[2, 5, 7, 0]]
D[[0, 3, 7, 7],[8, 0, 2, 3],[5, 8, 0, 1],[2, 5, 7, 0]]
Attempts:
2 left
💡 Hint
Check if going through intermediate nodes reduces the path cost.
🧠 Conceptual
intermediate
1:00remaining
Understanding Floyd Warshall Algorithm Complexity
What is the time complexity of the Floyd Warshall algorithm for a graph with V vertices?
AO(V^3)
BO(V^2)
CO(V^4)
DO(V log V)
Attempts:
2 left
💡 Hint
Consider the three nested loops over vertices.
🔧 Debug
advanced
2:00remaining
Identify the error in this Floyd Warshall implementation
What error will this code produce when run?
DSA Javascript
const INF = 99999;
const graph = [
  [0, 1, INF],
  [INF, 0, 2],
  [3, INF, 0]
];

function floydWarshall(graph) {
  const dist = graph.map(row => row.slice());
  const V = graph.length;
  for (let k = 0; k < V; k++) {
    for (let i = 0; i < V; i++) {
      for (let j = 0; j < V; j++) {
        if (dist[i][k] + dist[k][j] < dist[i][j]) {
          dist[i][j] = dist[i][k] + dist[k][j];
        }
      }
    }
  }
  return dist;
}

console.log(floydWarshall(graph));
AReferenceError: dist is not defined
BTypeError: Cannot read property of undefined
CRangeError: Maximum call stack size exceeded
DNo error, outputs shortest path matrix
Attempts:
2 left
💡 Hint
Check if the code uses valid indices and initialization.
❓ Predict Output
advanced
2:00remaining
Detecting negative cycles with Floyd Warshall
After running Floyd Warshall, how can you detect if the graph contains a negative weight cycle?
DSA Javascript
const INF = 99999;
const graph = [
  [0, 1, INF],
  [INF, 0, -1],
  [-1, INF, 0]
];

function floydWarshall(graph) {
  const dist = graph.map(row => row.slice());
  const V = graph.length;
  for (let k = 0; k < V; k++) {
    for (let i = 0; i < V; i++) {
      for (let j = 0; j < V; j++) {
        if (dist[i][k] + dist[k][j] < dist[i][j]) {
          dist[i][j] = dist[i][k] + dist[k][j];
        }
      }
    }
  }
  return dist;
}

const dist = floydWarshall(graph);
const hasNegativeCycle = dist.some((row, i) => row[i] < 0);
console.log(hasNegativeCycle);
Aundefined
Bfalse
Ctrue
DTypeError
Attempts:
2 left
💡 Hint
Check the diagonal elements of the distance matrix after running the algorithm.
🧠 Conceptual
expert
1:30remaining
Why Floyd Warshall is preferred over repeated Dijkstra for dense graphs?
Which reason best explains why Floyd Warshall is often preferred over running Dijkstra from each vertex in dense graphs?
ADijkstra cannot handle negative weights, Floyd Warshall can
BFloyd Warshall uses less memory than Dijkstra
CFloyd Warshall is easier to implement than Dijkstra
DFloyd Warshall has better time complexity O(V^3) compared to running Dijkstra V times with O(V^2 log V) in dense graphs
Attempts:
2 left
💡 Hint
Consider edge weights and algorithm capabilities.

Practice

(1/5)
1. What is the main purpose of the Floyd Warshall algorithm in graph theory?
easy
A. To detect cycles in a graph
B. To find the shortest path from a single source to all other vertices
C. To find the shortest paths between all pairs of vertices in a weighted graph
D. To sort vertices in topological order

Solution

  1. Step 1: Understand Floyd Warshall's goal

    The Floyd Warshall algorithm calculates shortest paths between every pair of vertices in a weighted graph.
  2. Step 2: Differentiate from other algorithms

    Unlike Dijkstra's algorithm which finds shortest paths from one source, Floyd Warshall finds paths for all pairs.
  3. Final Answer:

    To find the shortest paths between all pairs of vertices in a weighted graph -> Option C
  4. Quick Check:

    All pairs shortest path = Floyd Warshall [OK]
Hint: Floyd Warshall finds shortest paths for all vertex pairs [OK]
Common Mistakes:
  • Confusing with Dijkstra's single source shortest path
  • Thinking it detects cycles
  • Assuming it sorts vertices
2. Which of the following is the correct way to initialize the distance matrix dist for Floyd Warshall in JavaScript given a graph adjacency matrix graph?
easy
A. const dist = graph.map(row => row.slice());
B. const dist = graph.slice();
C. const dist = graph.map(row => row);
D. const dist = [...graph];

Solution

  1. Step 1: Understand deep copy necessity

    We need a deep copy of the 2D array so changes to dist do not affect graph.
  2. Step 2: Check each option for deep copy

    const dist = graph.map(row => row.slice()); uses map and slice to copy each row array, creating a deep copy. Others create shallow copies.
  3. Final Answer:

    const dist = graph.map(row => row.slice()); -> Option A
  4. Quick Check:

    Deep copy with map and slice = const dist = graph.map(row => row.slice()); [OK]
Hint: Use map with slice for deep copy of 2D arrays [OK]
Common Mistakes:
  • Using shallow copy causing original graph to change
  • Using spread operator which copies only top-level array
  • Using map without slice copying references
3. What will be the output distance matrix after running Floyd Warshall on the following graph adjacency matrix where Infinity means no direct edge?
const graph = [
  [0, 3, Infinity],
  [2, 0, 5],
  [Infinity, 1, 0]
];
medium
A. [[0, 3, 7], [2, 0, 5], [3, 1, 0]]
B. [[0, 3, 5], [2, 0, 5], [Infinity, 1, 0]]
C. [[0, 3, Infinity], [2, 0, 5], [3, 1, 0]]
D. [[0, 3, 8], [2, 0, 5], [3, 1, 0]]

Solution

  1. Step 1: Initialize dist matrix same as graph

    dist = [[0,3,∞],[2,0,5],[∞,1,0]]
  2. Step 2: Update dist using Floyd Warshall iterations

    Check paths through each vertex k=0,1,2:
    k=0: dist[2][0] = min(∞, dist[2][0]+dist[0][0])=∞ no change
    k=1: dist[0][2] = min(∞, dist[0][1]+dist[1][2])=3+5=8
    dist[2][0] = min(∞, dist[2][1]+dist[1][0])=1+2=3
    k=2: no shorter paths found
    Final dist = [[0,3,8],[2,0,5],[3,1,0]]
  3. Final Answer:

    [[0, 3, 8], [2, 0, 5], [3, 1, 0]] -> Option D
  4. Quick Check:

    Updated shortest paths matrix = [[0, 3, 8], [2, 0, 5], [3, 1, 0]] [OK]
Hint: Check all intermediate vertices to update shortest paths [OK]
Common Mistakes:
  • Not updating paths through intermediate vertices
  • Confusing Infinity with zero
  • Missing updates for indirect paths
4. Identify the error in this Floyd Warshall implementation snippet:
for (let k = 0; k < V; k++) {
  for (let i = 0; i < V; i++) {
    for (let j = 0; j < V; j++) {
      if (dist[i][k] + dist[k][j] < dist[i][j]) {
        dist[i][j] = dist[i][k] + dist[k][j];
      }
    }
  }
}
medium
A. Missing check if dist[i][k] or dist[k][j] is Infinity before addition
B. The loops should be reversed: i, j, then k
C. No error, the code is correct
D. The condition should use <= instead of <

Solution

  1. Step 1: Analyze addition of distances

    Adding dist[i][k] + dist[k][j] without checking if either is Infinity can cause incorrect results or overflow.
  2. Step 2: Identify missing Infinity checks

    Before adding, must ensure dist[i][k] !== Infinity and dist[k][j] !== Infinity to avoid invalid sums.
  3. Final Answer:

    Missing check if dist[i][k] or dist[k][j] is Infinity before addition -> Option A
  4. Quick Check:

    Check Infinity before sum to avoid errors [OK]
Hint: Always check for Infinity before adding distances [OK]
Common Mistakes:
  • Ignoring Infinity causing wrong updates
  • Changing loop order unnecessarily
  • Using <= instead of < causing redundant updates
5. Given a weighted directed graph with possible negative edges but no negative cycles, how does Floyd Warshall detect the presence of a negative cycle after running the algorithm?
hard
A. By checking if any dist[i][j] is Infinity
B. By checking if any diagonal element dist[i][i] becomes negative
C. By verifying if the sum of all distances is zero
D. By checking if any dist[i][j] is negative for i != j

Solution

  1. Step 1: Understand negative cycle effect on dist matrix

    Negative cycles cause the shortest path from a vertex to itself to become negative.
  2. Step 2: Check diagonal elements after Floyd Warshall

    If any dist[i][i] < 0, it means a negative cycle exists involving vertex i.
  3. Final Answer:

    By checking if any diagonal element dist[i][i] becomes negative -> Option B
  4. Quick Check:

    Negative cycle detected if dist[i][i] < 0 [OK]
Hint: Check diagonal dist[i][i] for negativity to find negative cycles [OK]
Common Mistakes:
  • Checking off-diagonal elements for negative cycles
  • Confusing Infinity with negative cycles
  • Assuming sum of distances indicates cycles
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard