Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the adjacency list for the graph.
DSA Go
graph := make(map[int][]int) graph[0] = []int{1, 2} graph[1] = []int{0, [1] graph[2] = []int{0}
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing node indices and adding wrong neighbors.
Forgetting that the graph is undirected, so edges go both ways.
✗ Incorrect
Node 1 is connected to nodes 0 and 2, so the adjacency list for node 1 should include 2.
2fill in blank
mediumComplete the code to mark a node as visited in the DFS function.
DSA Go
func dfs(node int, parent int, graph map[int][]int, visited map[int]bool) bool {
visited[node] = [1]
for _, neighbor := range graph[node] {
if !visited[neighbor] {
if dfs(neighbor, node, graph, visited) {
return true
}
} else if neighbor != parent {
return true
}
}
return false
}Attempts:
3 left
💡 Hint
Common Mistakes
Marking visited[node] as false instead of true.
Using nil or 0 which are invalid for boolean map values.
✗ Incorrect
We mark the current node as visited by setting visited[node] to true.
3fill in blank
hardFix the error in the DFS call inside the cycle detection function.
DSA Go
func hasCycle(graph map[int][]int) bool {
visited := make(map[int]bool)
for node := range graph {
if !visited[node] {
if dfs([1], -1, graph, visited) {
return true
}
}
}
return false
}Attempts:
3 left
💡 Hint
Common Mistakes
Passing the whole graph or visited map instead of a node.
Passing -1 as the starting node.
✗ Incorrect
The DFS should start from the current node in the loop, so the argument is node.
4fill in blank
hardFill both blanks to complete the condition that detects a cycle in DFS.
DSA Go
if visited[neighbor] && neighbor != [1] { return [2] }
Attempts:
3 left
💡 Hint
Common Mistakes
Returning false instead of true when a cycle is found.
Comparing neighbor to node instead of parent.
✗ Incorrect
If a neighbor is visited and is not the parent, it means a cycle is found, so return true.
5fill in blank
hardFill all three blanks to complete the main function that builds the graph and checks for cycles.
DSA Go
func main() {
graph := make(map[int][]int)
graph[0] = []int{1, [1]
graph[1] = []int{0, [2]
graph[2] = []int[3]
if hasCycle(graph) {
println("Cycle detected")
} else {
println("No cycle")
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up neighbors for nodes.
Using wrong indices causing no cycle detection.
✗ Incorrect
Node 0 connects to 1 and 2, node 1 connects to 0 and 1 (which is a self-loop, but here 1 is correct for cycle), node 2 connects to 0.
