Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the in-degree array with zeros.
DSA C++
vector<int> indegree(V, [1]);Attempts:
3 left
💡 Hint
Common Mistakes
Initializing in-degree with 1 or negative values causes wrong counts.
Using V as initial value leads to incorrect in-degree.
✗ Incorrect
The in-degree array should start with zero for all vertices because initially no edges are counted.
2fill in blank
mediumComplete the code to push nodes with zero in-degree into the queue.
DSA C++
for (int i = 0; i < V; i++) { if (indegree[i] [1] 0) { q.push(i); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' or '>' causes wrong nodes to be pushed.
Using '<' misses nodes with zero in-degree.
✗ Incorrect
We push nodes with zero in-degree because they have no dependencies and can be processed first.
3fill in blank
hardFix the error in the loop that decreases in-degree of adjacent nodes.
DSA C++
while (!q.empty()) { int node = q.front(); q.pop(); for (auto it : adj[node]) { indegree[it] [1] 1; if (indegree[it] == 0) { q.push(it); } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+=' increases in-degree incorrectly.
Using '=' assigns wrong values.
Using '*=' multiplies in-degree incorrectly.
✗ Incorrect
We decrease the in-degree by 1 for each adjacent node because one dependency is processed.
4fill in blank
hardFill both blanks to correctly add nodes to the result and check for cycle.
DSA C++
vector<int> topo; int count = 0; while (!q.empty()) { int node = q.front(); q.pop(); topo.[1](node); count[2] 1; for (auto it : adj[node]) { indegree[it] -= 1; if (indegree[it] == 0) { q.push(it); } } } if (count != V) { cout << "Cycle detected, topological sort not possible"; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop_back removes elements instead of adding.
Using '-=' decreases count incorrectly.
✗ Incorrect
We add the node to the topo vector using push_back and increase count by 1 to track processed nodes.
5fill in blank
hardFill all three blanks to print the topological order correctly.
DSA C++
for (int i = 0; i [1] topo.size(); i++) { cout << topo[i]; if (i [2] topo.size() - 1) { cout << [3]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' in loop condition causes only one iteration.
Printing arrow after last element causes formatting issues.
✗ Incorrect
We loop from 0 to less than topo.size(), print ' -> ' between nodes except after the last one.
