Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the distance array with infinity except the source vertex.
DSA Java
int[] dist = new int[V]; for (int i = 0; i < V; i++) { dist[i] = [1]; } dist[src] = 0;
Attempts:
3 left
💡 Hint
Common Mistakes
Setting distance to 0 for all vertices.
Using Integer.MIN_VALUE which is negative.
Not initializing the array before use.
✗ Incorrect
We initialize all distances to Integer.MAX_VALUE to represent infinity, except the source which is set to 0.
2fill in blank
mediumComplete the code to relax edges inside the main loop of Bellman-Ford.
DSA Java
for (int i = 1; i < V; i++) { for (Edge edge : edges) { int u = edge.src; int v = edge.dest; int weight = edge.weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight [1] dist[v]) { dist[v] = dist[u] + weight; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < in the condition.
Not checking if dist[u] is Integer.MAX_VALUE before adding.
Using == or != which are incorrect for relaxation.
✗ Incorrect
We relax edges if the current distance to u plus weight is less than the current distance to v.
3fill in blank
hardFix the error in the negative cycle detection condition.
DSA Java
for (Edge edge : edges) { int u = edge.src; int v = edge.dest; int weight = edge.weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight [1] dist[v]) { System.out.println("Graph contains negative weight cycle"); return; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using > which is incorrect for negative cycle detection.
Using == or != which do not detect cycles.
Not checking dist[u] != Integer.MAX_VALUE before comparison.
✗ Incorrect
If after V-1 iterations we can still relax an edge, it means a negative weight cycle exists, so dist[u] + weight < dist[v].
4fill in blank
hardFill both blanks to correctly update the distance array and check for overflow.
DSA Java
if (dist[u] != Integer.MAX_VALUE && dist[u] [1] weight < dist[v]) { dist[v] = dist[u] [2] weight; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition.
Using > instead of < in the condition.
Not updating dist[v] correctly.
✗ Incorrect
We add weight to dist[u] to get the new distance and check if it is less than dist[v] to update.
5fill in blank
hardFill all three blanks to complete the code that prints the shortest distances after Bellman-Ford.
DSA Java
for (int i = 0; i < V; i++) { if (dist[i] == [1]) { System.out.println("Vertex " + i + ": unreachable"); } else { System.out.println("Vertex " + i + ": " + dist[[2]]); } } return [3];
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong constant for infinity check.
Using wrong index in print statement.
Not returning the distance array.
✗ Incorrect
We check if dist[i] == Integer.MAX_VALUE to represent infinity (unreachable), print unreachable, else print dist[i], then return dist array.
