Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the distance to the source vertex as zero.
DSA Python
dist = [float('inf')] * V dist[[1]] = 0
Attempts:
3 left
💡 Hint
Common Mistakes
Setting distance of a wrong vertex to zero.
Using negative index for source vertex.
✗ Incorrect
The distance to the source vertex itself is zero, so dist[0] = 0.
2fill in blank
mediumComplete the code to relax edges inside the main loop.
DSA Python
for _ in range(V - 1): for u, v, w in edges: if dist[u] != float('inf') and dist[u] + w [1] dist[v]: dist[v] = dist[u] + w
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < in the condition.
Not checking if dist[u] is infinity.
✗ Incorrect
Relaxation updates dist[v] if a shorter path is found, so we check if dist[u] + w < dist[v].
3fill in blank
hardFix the error in the negative cycle detection condition.
DSA Python
for u, v, w in edges: if dist[u] != float('inf') and dist[u] + w [1] dist[v]: return True # Negative cycle detected
Attempts:
3 left
💡 Hint
Common Mistakes
Using >= or > instead of < in the condition.
Not checking if dist[u] is infinity.
✗ Incorrect
If after V-1 relaxations, dist[u] + w < dist[v], it means a negative cycle exists.
4fill in blank
hardFill both blanks to complete the relaxation update and condition.
DSA Python
for _ in range(V - 1): for u, v, w in edges: if dist[u] != float('inf') and dist[u] + w [1] dist[v]: dist[v] = dist[u] [2] w
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < in condition.
Using - instead of + for updating distance.
✗ Incorrect
Relax if dist[u] + w < dist[v], then update dist[v] = dist[u] + w.
5fill in blank
hardFill all three blanks to complete the negative cycle detection and return statement.
DSA Python
for u, v, w in edges: if dist[u] != float('inf') and dist[u] + w [1] dist[v]: print('Graph contains a negative weight cycle') return [2] return [3]
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < in condition.
Returning False when cycle is detected.
✗ Incorrect
If dist[u] + w < dist[v], negative cycle exists, so return True; otherwise, return False.
