Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start DFS from the given node.
DSA Javascript
function dfs(graph, start) {
const visited = new Set();
function explore(node) {
if (visited.has(node)) return;
visited.add(node);
for (const neighbor of graph[node]) {
explore(neighbor);
}
}
explore([1]);
return visited;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'graph' instead of 'start' as the initial node.
Using 'node' which is undefined in this scope.
Using 'visited' which is a Set, not a node.
✗ Incorrect
The DFS starts from the given 'start' node, so we call explore(start).
2fill in blank
mediumComplete the code to check if a node has been visited before exploring.
DSA Javascript
function explore(node) {
if ([1]) return;
visited.add(node);
for (const neighbor of graph[node]) {
explore(neighbor);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'visited.add(node)' which adds instead of checks.
Using 'node in visited' which does not work for Set.
Using 'graph.has(node)' which checks graph keys, not visited nodes.
✗ Incorrect
We check if the node is already in the visited set using visited.has(node).
3fill in blank
hardFix the error in the loop that visits neighbors of the current node.
DSA Javascript
for (const neighbor of [1]) { explore(neighbor); }
Attempts:
3 left
💡 Hint
Common Mistakes
Looping over 'graph' which is the whole graph object.
Looping over 'visited' which is a Set of visited nodes.
Looping over 'node' which is a single node, not iterable.
✗ Incorrect
We need to loop over the neighbors of the current node, which are in graph[node].
4fill in blank
hardFill both blanks to create a DFS function that returns the visited nodes set.
DSA Javascript
function dfs(graph, [1]) { const visited = new Set(); function explore(node) { if (visited.has(node)) return; visited.add(node); for (const neighbor of graph[node]) { explore(neighbor); } } explore([2]); return visited; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for parameter and call.
Using 'graph' or 'visited' instead of the start node.
✗ Incorrect
The parameter is 'start' and we call explore(start) to begin DFS.
5fill in blank
hardFill all three blanks to create a DFS that collects nodes in order visited in an array.
DSA Javascript
function dfs(graph, [1]) { const visited = new Set(); const order = []; function explore(node) { if (visited.has(node)) return; visited.add(node); order.push([2]); for (const neighbor of graph[node]) { explore(neighbor); } } explore([3]); return order; }
Attempts:
3 left
💡 Hint
Common Mistakes
Pushing 'start' instead of 'node' to order.
Calling explore with 'node' which is undefined outside.
Using 'visited' instead of node or start.
✗ Incorrect
Parameter is 'start', we push 'node' to order, and call explore(start).
