Step 1: Identify adjacency list entries for node 1
Node 1 has edges to node 2 only, so graph[1] = {2}.
Step 2: Understand fmt.Println output
Printing graph[1] outputs the slice [2].
Final Answer:
[2] -> Option B
Quick Check:
graph[1] = [2] [OK]
Hint: Print adjacency list for node key directly [OK]
Common Mistakes:
Confusing keys and values in map
Assuming node 1 connects to node 0
Expecting adjacency matrix output
4. The following Go code attempts to create an adjacency matrix but has a bug. What is the bug?
graph := make([][]int, 3)
for i := range graph {
graph[i] = make([]int, 3)
}
graph[0][1] = 1
graph[1][2] = 1
fmt.Println(graph[0][2])
medium
A. The matrix is not initialized properly
B. graph[0][2] should be 1 but prints 0
C. Index out of range error
D. No bug, code runs correctly
Solution
Step 1: Check matrix initialization
Each row is initialized with make([]int, 3), so matrix is properly created.
Step 2: Check assigned values and print
graph[0][1] and graph[1][2] are set to 1; graph[0][2] was never set, so prints 0.
Step 3: Verify no runtime errors
All indices are within range; no errors occur.
Final Answer:
No bug, code runs correctly -> Option D
Quick Check:
Proper initialization and indexing = No bug [OK]
Hint: Check initialization and index ranges carefully [OK]
Common Mistakes:
Assuming unassigned entries print 1
Thinking initialization is missing
Expecting index errors without out-of-range access
5. You need to represent a dense graph with 1000 nodes where you frequently check if an edge exists between any two nodes. Which data structure is best and why?
A) Adjacency Matrix for constant-time edge checks
B) Adjacency List for memory efficiency
C) Edge List for simple iteration
D) Map of maps for flexible keys
hard
A. Edge List for simple iteration
B. Adjacency List for memory efficiency
C. Adjacency Matrix for constant-time edge checks
D. Map of maps for flexible keys
Solution
Step 1: Understand graph density and operations
A dense graph has many edges, close to the maximum possible.
Step 2: Choose data structure for fast edge existence checks
Adjacency matrix allows O(1) time to check if edge exists between any two nodes.
Step 3: Consider memory tradeoff
Though adjacency matrix uses more memory, for dense graphs this is acceptable and beneficial.
Final Answer:
Adjacency Matrix for constant-time edge checks -> Option C
Quick Check:
Dense graph + fast edge check = Adjacency Matrix [OK]