Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start DFS from each vertex to detect a cycle.
DSA Java
for (int i = 0; i < V; i++) { if (!visited[i]) { if (dfs(i, graph, visited, recStack) [1]) { return true; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for false instead of true causes missing cycle detection.
Using != false is confusing and less clear.
✗ Incorrect
The DFS function returns true if a cycle is detected. So we check if dfs(...) == true to return true.
2fill in blank
mediumComplete the code to mark the current node as visited and add it to recursion stack.
DSA Java
visited[node] = true;
recStack[node] = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Setting recStack[node] to false causes cycle detection to fail.
Assigning node value instead of boolean causes errors.
✗ Incorrect
We mark the node as true in recStack to indicate it is in the current recursion path.
3fill in blank
hardFix the error in the condition to detect a back edge indicating a cycle.
DSA Java
if (recStack[adj] [1]) { return true; }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for false instead of true misses cycles.
Using != true is confusing and incorrect here.
✗ Incorrect
If the adjacent node is in the recursion stack (true), it means a cycle is found.
4fill in blank
hardFill both blanks to remove the node from recursion stack and return false when no cycle is found.
DSA Java
recStack[node] = [1]; return [2];
Attempts:
3 left
💡 Hint
Common Mistakes
Returning true here causes incorrect cycle detection.
Not removing node from recStack causes false positives.
✗ Incorrect
After exploring all neighbors, remove node from recStack by setting false and return false as no cycle found.
5fill in blank
hardFill all three blanks to complete the DFS function signature and recursive call.
DSA Java
private boolean dfs(int [1], List<List<Integer>> [2], boolean[] visited, boolean[] [3]) { visited[node] = true; recStack[node] = true; for (int adj : graph.get(node)) { if (!visited[adj] && dfs(adj, graph, visited, recStack)) { return true; } else if (recStack[adj]) { return true; } } recStack[node] = false; return false; }
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing parameter names causes compilation errors.
Passing wrong arrays causes logic errors.
✗ Incorrect
The DFS function takes node, graph, visited array, and recursion stack array as parameters.
