Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the visited array for all nodes.
DSA Javascript
const visited = new Array(n).fill([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Initializing visited with true causes all nodes to be considered visited from the start.
Using 0 or null can cause confusion in boolean checks.
✗ Incorrect
We initialize the visited array with false because no nodes have been visited at the start.
2fill in blank
mediumComplete the code to mark the current node as visited in the DFS function.
DSA Javascript
visited[node] = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Setting visited[node] to false again causes infinite loops.
Using null or 0 does not correctly mark the node as visited.
✗ Incorrect
Marking visited[node] as true means we have now visited this node during DFS.
3fill in blank
hardFix the error in the condition that detects a cycle when a node is in the recursion stack.
DSA Javascript
if (recStack[neighbor] === [1]) { return true; }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for false or null will not detect cycles correctly.
Using undefined causes runtime errors.
✗ Incorrect
If the neighbor is already in the recursion stack (true), it means a cycle is detected.
4fill in blank
hardFill both blanks to correctly remove the node from recursion stack and mark it as visited after DFS.
DSA Javascript
recStack[node] = [1]; visited[node] = [2];
Attempts:
3 left
💡 Hint
Common Mistakes
Setting recStack[node] to true causes false cycle detection.
Marking visited[node] as false causes repeated visits.
✗ Incorrect
After DFS, we remove the node from recursion stack by setting recStack[node] to false and mark it visited by setting visited[node] to true.
5fill in blank
hardFill all three blanks to complete the DFS function header and recursive call.
DSA Javascript
function dfs([1], graph, visited, recStack) { recStack[node] = true; for (const [2] of graph[node]) { if (!visited[neighbor] && dfs([3], graph, visited, recStack)) { return true; } } recStack[node] = false; visited[node] = true; return false; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node' instead of 'neighbor' in the loop or recursive call causes errors.
Mixing variable names leads to undefined variables.
✗ Incorrect
The DFS function takes 'node' as parameter, loops over neighbors using 'neighbor', and recursively calls dfs with 'neighbor'.
