Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the distance array with Infinity for all vertices except the source.
DSA Javascript
const distances = Array(vertices).fill([1]); distances[source] = 0;
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 for all distances causes incorrect shortest path calculations.
Using null or -Infinity is not appropriate for initial distances.
✗ Incorrect
We use Infinity to represent initially unknown distances, except the source which is 0.
2fill in blank
mediumComplete the code to relax edges inside the main loop of Bellman-Ford.
DSA Javascript
for (let i = 0; i < vertices - 1; i++) { for (const [u, v, weight] of edges) { if (distances[u] !== Infinity && distances[u] + weight [1] distances[v]) { distances[v] = distances[u] + weight; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < reverses the logic and breaks the algorithm.
Using === or !== is incorrect for comparing distances.
✗ Incorrect
We update distances[v] if the new path is shorter, so we check if distances[u] + weight < distances[v].
3fill in blank
hardFix the error in the negative cycle detection loop condition.
DSA Javascript
for (const [u, v, weight] of edges) { if (distances[u] !== Infinity && distances[u] + weight [1] distances[v]) { return true; // Negative cycle detected } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using >= or > will not correctly detect negative cycles.
Using <= reverses the logic and misses cycles.
✗ Incorrect
To detect a negative cycle, we check if we can still relax an edge, meaning distances[u] + weight < distances[v].
4fill in blank
hardFill both blanks to complete the function signature and return statement for Bellman-Ford.
DSA Javascript
function bellmanFord([1], edges, source) { const distances = Array([2]).fill(Infinity); distances[source] = 0; // ... rest of the algorithm return distances; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using edges or source as the size causes errors.
Using vertices.length assumes vertices is an array, but it's a number.
✗ Incorrect
The function takes the number of vertices as 'vertices' and initializes distances array with that size.
5fill in blank
hardFill all three blanks to complete the edge relaxation and negative cycle detection in Bellman-Ford.
DSA Javascript
for (let i = 0; i < [1] - 1; i++) { for (const [u, v, weight] of edges) { if (distances[u] !== Infinity && distances[u] + weight [2] distances[v]) { distances[v] = distances[u] + weight; } } } for (const [u, v, weight] of edges) { if (distances[u] !== Infinity && distances[u] + weight [3] distances[v]) { return true; // Negative cycle detected } } return false;
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < breaks relaxation logic.
Looping wrong number of times misses shortest paths.
✗ Incorrect
We loop vertices-1 times, relax edges if new distance is less, and detect negative cycles if relaxation is still possible.
