Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add the current node to the stack after visiting all its neighbors.
DSA Javascript
function dfs(node, visited, stack, graph) {
visited.add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
dfs(neighbor, visited, stack, graph);
}
}
stack.[1](node);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push removes elements instead of adding.
Using shift or unshift changes the order incorrectly.
✗ Incorrect
We add the node to the stack after visiting all neighbors using push to maintain the correct order for topological sort.
2fill in blank
mediumComplete the code to mark a node as visited before exploring its neighbors.
DSA Javascript
function dfs(node, visited, stack, graph) {
[1].add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
dfs(neighbor, visited, stack, graph);
}
}
stack.push(node);
}Attempts:
3 left
💡 Hint
Common Mistakes
Trying to add the node to the stack before visiting neighbors.
Adding the node to the graph object instead of visited set.
✗ Incorrect
We mark the node as visited by adding it to the visited set before exploring neighbors.
3fill in blank
hardFix the error in the loop that iterates over all nodes to start DFS if not visited.
DSA Javascript
function topologicalSort(graph) {
const visited = new Set();
const stack = [];
for (const node [1] Object.keys(graph)) {
if (!visited.has(node)) {
dfs(node, visited, stack, graph);
}
}
return stack.reverse();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' which iterates over keys of an object, not array elements.
Using '=' which is assignment, not iteration.
✗ Incorrect
Use 'of' to iterate over the array returned by Object.keys(graph) in a for...of loop.
4fill in blank
hardFill both blanks to correctly initialize the graph and call topologicalSort.
DSA Javascript
const graph = [1]; const result = topologicalSort([2]); console.log(result);
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a string instead of the graph object to the function.
Using an undefined variable instead of graph.
✗ Incorrect
Initialize graph with the correct adjacency list and pass it to topologicalSort function.
5fill in blank
hardFill all three blanks to complete the DFS function with cycle detection.
DSA Javascript
function dfs(node, visited, stack, graph, temp) {
if (temp.has(node)) throw new Error('Cycle detected');
if (!visited.has(node)) {
temp.add(node);
for (const neighbor of graph[[1]]) {
dfs(neighbor, visited, stack, graph, temp);
}
temp.[2](node);
visited.[3](node);
stack.push(node);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong method names like 'remove' which does not exist on Set.
Accessing neighbors with wrong variable.
✗ Incorrect
Use 'node' to access neighbors, remove node from temp set with 'delete', and add node to visited set with 'add'.
