What is an adjacency list in graph representation?
An adjacency list is a way to represent a graph where each node stores a list of its neighbors. It shows which nodes are directly connected to each node.
Click to reveal answer
intermediate
How does an adjacency list differ from an adjacency matrix?
An adjacency list stores neighbors only, saving space for sparse graphs. An adjacency matrix uses a 2D array showing connections between all pairs, using more space.
Click to reveal answer
beginner
TypeScript code snippet: How to declare an adjacency list for a graph with 3 nodes?
Thinking Map keys must be strings (numbers are allowed)
Ignoring runtime error from push on undefined
5. You want to represent a directed graph with nodes 1 to 4 using an adjacency list in TypeScript. Which code correctly adds an edge from node 2 to node 4 without affecting other edges?
const graph: Map = new Map();
graph.set(1, [2]);
graph.set(2, [3]);
graph.set(3, []);
graph.set(4, []);
// Add edge from 2 to 4 here
hard
A. graph.get(2)?.push(4);
B. graph.set(2, [4]);
C. graph.set(4, [2]);
D. graph.get(4)?.push(2);
Solution
Step 1: Understand existing edges
Node 2 currently has neighbors [3]. We want to add 4 without removing 3.
Step 2: Choose correct method to add edge
Using graph.get(2)?.push(4) adds 4 to existing array, preserving [3]. graph.set(2, [4]) replaces neighbors, removing 3.
Final Answer:
graph.get(2)?.push(4); -> Option A
Quick Check:
Use push to add edge without overwriting [OK]
Hint: Use push on existing neighbors to add edges safely [OK]
Common Mistakes:
Overwriting neighbors array with set instead of pushing
Adding edge to wrong node
Confusing direction of edge in directed graph
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.