Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Adjacency List itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)An adjacency list stores only real neighbors for every declared vertex. Choose lists or sets from edge multiplicity and order requirements, allocate containers independently, and charge sorting separately when deterministic neighbor output is required.
1 practice exercise4 interview problems
Recognize it when The graph is sparse or traversal enumerates existing neighbors repeatedly.
Checking your account…
An adjacency list stores, for each vertex, only the neighbors connected by real edges. Its memory tracks graph content instead of every possible vertex pair.
Allocate one neighbor collection for every vertex, including isolated ones. Lists preserve edge order and duplicates; sets enforce unique membership. For an undirected graph, store both directions. Space is O(V + E), counting each undirected edge twice.
Choose direction and duplicate policy before insertion. Independent list allocation matters:
[[]] * node_count aliases all neighbor lists. Sort only if deterministic neighbor order belongs to
the output or traversal contract.
def build_adjacency_list(node_count, edges):
adjacency = [set() for _ in range(node_count)]
for left, right in edges:
adjacency[left].add(right)
adjacency[right].add(left)
return [sorted(neighbors) for neighbors in adjacency]Implement build_adjacency_list(node_count, edges). Deduplicate undirected edges, preserve isolated vertices, and sort neighbors. node_count is a nonnegative integer; every edge endpoint is in 0 <= endpoint < node_count.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def build_adjacency_list(node_count, edges):
adjacency = [set() for _ in range(node_count)]
for left, right in edges:
adjacency[left].add(right)
adjacency[right].add(left)
return [sorted(neighbors) for neighbors in adjacency]The existing builder receives reverse duplicate edges plus one isolated vertex. A set stores the relationship once, while separate containers keep vertex 3 empty. The final sort changes display order, not connectivity.
print(build_adjacency_list(4, [(0, 2), (2, 0), (2, 1)])) followed by print(build_adjacency_list(2, []))
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | adjacency = [set() for _ in range(node_count)] |
four distinct empty neighbor sets |
Every declared vertex receives storage, even an isolate. |
| 2 | adjacency[left].add(right); adjacency[right].add(left) |
edge (0, 2): neighbors 0 = {2}; neighbors 2 = {0} |
An undirected edge creates two stored directions. |
| 3 | adjacency[left].add(right); adjacency[right].add(left) |
reverse edge (2, 0): neighbor sets unchanged |
Set equality collapses duplicate logical relationships. |
| 4 | adjacency[left].add(right); adjacency[right].add(left) |
edge (2, 1): neighbors 2 = {0, 1}; neighbors 1 = {2}; neighbors 3 = set() |
Only the incident vertex containers change. |
| 5 | return [sorted(neighbors) for neighbors in adjacency] |
result = [[2], [2], [0, 1], []] |
Sorting each independent set supplies deterministic neighbor output. |
| Output | |
|---|---|
| 1 | [[2], [2], [0, 1], []] |
| 2 | [[], []] |
The sparse representation has one vertex slot plus stored neighbor entries, rather than every possible vertex pair. Its deterministic output requires per-neighbor-list sorting, which belongs in the complexity explanation.
DFS or BFS enumerates only existing edges. With discovery-time visited marking, reachability is O(V + E), unlike scanning a full matrix row for every visited vertex.
def reachable_vertices(adjacency, start):
seen = {start}
stack = [start]
while stack:
node = stack.pop()
for neighbor in adjacency[node]:
if neighbor not in seen:
seen.add(neighbor)
stack.append(neighbor)
return sorted(seen)Implement reachable_vertices(adjacency, start). Return all reachable vertices sorted, using explicit visited state. adjacency has valid neighbor indices and a valid start with 0 <= start < len(adjacency); it must be nonempty and has no -1 sentinel.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def reachable_vertices(adjacency, start):
seen = {start}
stack = [start]
while stack:
node = stack.pop()
for neighbor in adjacency[node]:
if neighbor not in seen:
seen.add(neighbor)
stack.append(neighbor)
return sorted(seen)Choose a list for sparse graphs and neighbor iteration. Choose a matrix for dense graphs or many constant-time edge-existence queries. A set-backed list improves duplicate checks but adds hashing cost and loses authored order.
State direction, duplicate policy, and neighbor container. Explain O(V + E) by charging each stored neighbor entry once, then distinguish representation space from traversal space.
Build Graph Representations(opens in a new tab) isolates storage; Course Schedule(opens in a new tab) uses a directed adjacency list for prerequisites.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Adjacency List itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Build sorted adjacency lists | O(V + E + sum(d * log(d + 1))) | O(V + E * V + sum(d * log(d + 1))) | d is each distinct neighbor count; average assumes ordinary hashing. Repeated edges do not add output multiplicity. |
| Return sorted reachable vertices | O(R + E_R + R * log(R + 1)) | O((R + E_R) * R + R * log(R + 1)) | R reachable vertices and E_R examined neighbor entries; input storage excluded. Sorting and collision behavior are counted. |
O(V + E) for build sorted adjacency lists; O(R) for return sorted reachable vertices.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Repeating one empty list makes all vertex slots reference the same neighbors.
Prevent it: Construct one list per vertex instead of multiplying an inner container.
adjacency = [[]] * node_count
adjacency[0].append(1)adjacency = [[] for _ in range(node_count)]
adjacency[0].append(1)Where you will hit this: Build Graph Representations(opens in a new tab)
A stored source-to-target entry alone represents a directed edge.
Prevent it: Insert both directions when constructing the undirected list.
adjacency[left].append(right)adjacency[left].append(right)
adjacency[right].append(left)Where you will hit this: Build Graph Representations(opens in a new tab)
A list append records repeated copies and changes degree and traversal work when the Lab expects one relationship.
Prevent it: Use set membership when repeated edges must collapse.
stored = list(neighbors)stored = sorted(set(neighbors))Where you will hit this: Course Schedule(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27