Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the in-degree array with zeros for all vertices.
DSA Javascript
const inDegree = new Array(V).fill([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 instead of 0, which incorrectly assumes each vertex has an incoming edge.
Using null or undefined which are not numbers and cause errors.
✗ Incorrect
We initialize the in-degree array with zeros because initially no edges have been processed.
2fill in blank
mediumComplete the code to increase the in-degree count for each neighbor in the adjacency list.
DSA Javascript
for (const neighbor of adj[node]) { inDegree[neighbor] [1] 1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using -= which would decrease the count incorrectly.
Using *= or /= which are not appropriate for counting.
✗ Incorrect
We add 1 to the in-degree of each neighbor because each edge increases the count of incoming edges.
3fill in blank
hardFix the error in the queue initialization to start with all vertices having zero in-degree.
DSA Javascript
const queue = []; for (let i = 0; i < V; i++) { if (inDegree[i] [1] 0) { queue.push(i); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using != or > which would select wrong vertices.
Using < which is incorrect for this condition.
✗ Incorrect
Vertices with zero in-degree have no dependencies and should be added to the queue to start processing.
4fill in blank
hardFill both blanks to correctly update in-degree and add new zero in-degree vertices to the queue.
DSA Javascript
while (queue.length > 0) { const node = queue.shift(); result.push(node); for (const neighbor of adj[node]) { inDegree[neighbor] [1] 1; if (inDegree[neighbor] [2] 0) { queue.push(neighbor); } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Increasing in-degree instead of decreasing.
Using incorrect comparison operators in the if condition.
✗ Incorrect
We decrease the in-degree by 1 when an edge is removed and check if it becomes zero to add the vertex to the queue.
5fill in blank
hardFill all three blanks to complete the topological sort function using Kahn's Algorithm.
DSA Javascript
function kahnTopologicalSort(V, adj) {
const inDegree = new Array(V).fill([1]);
for (let i = 0; i < V; i++) {
for (const neighbor of adj[i]) {
inDegree[neighbor] [2] 1;
}
}
const queue = [];
for (let i = 0; i < V; i++) {
if (inDegree[i] [3] 0) queue.push(i);
}
const result = [];
while (queue.length > 0) {
const node = queue.shift();
result.push(node);
for (const neighbor of adj[node]) {
inDegree[neighbor] -= 1;
if (inDegree[neighbor] === 0) queue.push(neighbor);
}
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong operators for increment or comparison.
Not initializing in-degree correctly.
✗ Incorrect
Initialize in-degree with 0, increment in-degree for neighbors, and enqueue vertices with zero in-degree.
