Skip to contentKEEP THE CRAFTTHE SANCTUARY

Adjacency List

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…

Adjacency List Code Labs

Mental Model

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.

Store Only Existing Neighbors

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.

Build Directed and Undirected Lists

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.

Build an Undirected Adjacency List

Reference
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]
Practice

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.

Public tests

  • Verify independent complete vertex storage

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Build an Undirected Adjacency List

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]

Trace Sparse Neighbor Ownership and Deduplication

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.
Print 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.

Traverse Sparse Neighborhoods

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.

Traverse Sparse Neighbors

Reference
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)
Practice

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.

Public tests

  • Verify traversal beyond direct neighbors

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Traverse Sparse Neighbors

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 List or Matrix

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.

Adjacency Direction and Ownership Mistakes

  • Omitting isolated vertices makes vertex identity depend on appearing in an edge.
  • Adding one direction for an undirected edge breaks reachability.
  • Aliased neighbor lists connect unrelated vertices.
  • Marking visited after removal permits duplicate frontier entries.

Explain It in an Interview

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 Version Note

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)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Build sorted adjacency listsO(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 verticesO(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.

Space

O(V + E) for build sorted adjacency lists; O(R) for return sorted reachable vertices.

Assumptions

  • d is each distinct neighbor count; average assumes ordinary hashing. Repeated edges do not add output multiplicity.
  • R reachable vertices and E_R examined neighbor entries; input storage excluded. Sorting and collision behavior are counted.

Invariants Worth Saying Aloud

  1. Each vertex owns its own neighbor collection, including isolates.
  2. Undirected builder inserts both directions and deduplicates repeated edges.
  3. Reachability marks discovery once; the returned list adds sorting work beyond traversal.

When To Use Or Avoid Adjacency List

Use It When

  • Use one independent neighbor collection per vertex for sparse traversal.
  • Use sets when repeated edges must collapse, then sort only for the output contract.

Choose Another Tool When

  • Use a matrix for small dense graphs with many arbitrary edge-existence queries.
  • Do not discard edge multiplicity when parallel edges belong to the model.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Aliasing every vertex's neighbor list

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.

Avoid

adjacency = [[]] * node_count
adjacency[0].append(1)

Use instead

adjacency = [[] for _ in range(node_count)]
adjacency[0].append(1)

Omitting the reverse undirected neighbor

A stored source-to-target entry alone represents a directed edge.

Prevent it: Insert both directions when constructing the undirected list.

Avoid

adjacency[left].append(right)

Use instead

adjacency[left].append(right)
adjacency[right].append(left)

Keeping duplicate edges in a deduplicated contract

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.

Avoid

stored = list(neighbors)

Use instead

stored = sorted(set(neighbors))

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.