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 Python
dist = [[1]] * V source = 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of infinity causes incorrect shortest path calculations.
Using None causes errors during comparisons.
✗ Incorrect
We initialize distances to infinity to represent that initially all vertices are unreachable except the source.
2fill in blank
mediumComplete the code to perform topological sorting using DFS.
DSA Python
def topological_sort_util(v, visited, stack): visited[v] = True for i in graph[v]: if not visited[i[0]]: topological_sort_util(i[0], visited, stack) stack.[1](v)
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop removes elements instead of adding.
Using insert without index causes errors.
✗ Incorrect
We append the vertex to the stack after visiting all its neighbors to maintain topological order.
3fill in blank
hardFix the error in the relaxation step inside the shortest path calculation.
DSA Python
for node in stack[::-1]: if dist[node] != float('inf'): for neighbor, weight in graph[node]: if dist[neighbor] [1] dist[node] + weight: dist[neighbor] = dist[node] + weight
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' causes no updates and wrong shortest paths.
Using '>=' may cause unnecessary updates.
✗ Incorrect
Relaxation updates the distance if the new path is shorter, so we check if current distance is greater than new path.
4fill in blank
hardFill both blanks to complete the initialization and topological sort call.
DSA Python
visited = [[1]] * V stack = [] for i in range(V): if not visited[i]: topological_sort_util(i, visited, [2])
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing visited with True causes skipping all nodes.
Passing visited instead of stack causes errors.
✗ Incorrect
We initialize visited with False and pass stack to collect topological order.
5fill in blank
hardFill all three blanks to complete the shortest path function using topological order.
DSA Python
def shortest_path(graph, V, source): dist = [float('inf')] * V dist[[1]] = 0 visited = [False] * V stack = [] for i in range(V): if not visited[i]: topological_sort_util(i, visited, stack) for node in stack[[2]]: if dist[node] != float('inf'): for neighbor, weight in graph[node]: if dist[neighbor] > dist[node] + [3]: dist[neighbor] = dist[node] + weight return dist
Attempts:
3 left
💡 Hint
Common Mistakes
Not reversing stack causes incorrect order processing.
Using wrong index for source distance initialization.
Using wrong variable instead of weight in relaxation.
✗ Incorrect
Set distance of source to 0, process nodes in reverse topological order, and use edge weight for relaxation.
