← Back to Algorithms, page 4

algorithms-0064 · Easy fresher

Represent a graph in code: build an adjacency list from an edge list, compare it with an adjacency matrix, and compute degrees.

An adjacency list stores, for every node, the list of its neighbours: O(V + E) space and neighbour iteration in O(degree). An adjacency matrix uses O(V^2) space but answers "is there an edge u-v" in O(1). For undirected graphs add each edge in both directions; for weighted graphs store (neighbour, weight) pairs. Most interview graphs are sparse, so the list is the default.

Full answer

Problem

Given n nodes labelled 0..n-1 and a list of edges, build a structure that lets algorithms iterate over each node's neighbours. Support directed, undirected and weighted edges, and compute degrees.

Example: n = 4, edges [(0, 1), (0, 2), (1, 2), (2, 3)] undirected gives [[1, 2], [0, 2], [0, 1, 3], [2]] and degrees [2, 2, 3, 1].

Constraints: up to 10^5 nodes and 2 * 10^5 edges, so the representation must be close to linear in size.

Brute force

Keep only the raw edge list. Finding the neighbours of one node scans all E edges, so a BFS or DFS becomes O(V * E).

Optimal approach

Adjacency list: adj = [[] for _ in range(n)]; for each (u, v) append v to adj[u] and, if undirected, u to adj[v]. For labels that are strings or sparse ids, use defaultdict(list). For weights, append (v, w).

Adjacency matrix: an n x n grid of 0/1 (or weights). Use it when the graph is small and dense or when edge-existence tests dominate.

Why it works

Graph algorithms mostly ask "who are the neighbours of u". The adjacency list answers that by indexing once and iterating exactly deg(u) entries, so a full traversal touches each edge a constant number of times. The sum of all degrees in an undirected graph is 2E (each edge is stored twice), which is why space is O(V + E).

Complexity

ListMatrix
SpaceO(V + E)O(V^2)
Neighbours of uO(deg u)O(V)
Edge test u-vO(deg u), or O(1) with setsO(1)
BuildO(V + E)O(V^2)

Code

python
from collections import defaultdict


def build_adjacency(n, edges, directed=False):
    """Adjacency list as a list of lists. O(V + E) space; neighbours of u in O(deg(u))."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
        if not directed:
            adj[v].append(u)
    return adj


def build_weighted(edges, directed=True):
    """Dict of lists for sparse or non-integer node ids: {u: [(v, w), ...]}."""
    adj = defaultdict(list)
    for u, v, w in edges:
        adj[u].append((v, w))
        if not directed:
            adj[v].append((u, w))
    return adj


def build_matrix(n, edges, directed=False):
    """Adjacency matrix: O(V^2) space, O(1) edge test. Fine for small dense graphs."""
    m = [[0] * n for _ in range(n)]
    for u, v in edges:
        m[u][v] = 1
        if not directed:
            m[v][u] = 1
    return m


def degrees(adj):
    return [len(nbrs) for nbrs in adj]


def in_degrees(n, adj):
    indeg = [0] * n
    for u in range(n):
        for v in adj[u]:
            indeg[v] += 1
    return indeg


if __name__ == "__main__":
    edges = [(0, 1), (0, 2), (1, 2), (2, 3)]
    adj = build_adjacency(4, edges)
    assert adj == [[1, 2], [0, 2], [0, 1, 3], [2]]
    assert degrees(adj) == [2, 2, 3, 1]
    assert sum(degrees(adj)) == 2 * len(edges)            # handshake lemma
    dadj = build_adjacency(4, edges, directed=True)
    assert dadj == [[1, 2], [2], [3], []]
    assert in_degrees(4, dadj) == [0, 1, 2, 1]
    m = build_matrix(4, edges)
    assert all(m[u][v] == (v in adj[u]) for u in range(4) for v in range(4))
    w = build_weighted([("a", "b", 5), ("b", "c", 2)])
    assert w["a"] == [("b", 5)] and w["c"] == []
    assert build_adjacency(3, []) == [[], [], []]         # isolated nodes still get a list
    print("all tests passed")

Save as b64_adjacency_list.py and run python3 b64_adjacency_list.py. It prints all tests passed (Python 3.13.5).

Edge cases

Isolated nodes (still need an empty list, or a later lookup fails). Self-loops (appear once or twice depending on the convention; agree on it). Parallel edges (lists keep both; sets merge them). 1-indexed input (allocate n + 1 or shift labels).

Pattern

Choosing the graph representation before writing the algorithm. Lists suit BFS, DFS, Dijkstra and topological sort; matrices suit Floyd-Warshall and dense bitset tricks; edge lists suit Kruskal and Bellman-Ford. Grids are implicit graphs where neighbours are computed from coordinates.

python
from collections import defaultdict


def build_adjacency(n, edges, directed=False):
    """Adjacency list as a list of lists. O(V + E) space; neighbours of u in O(deg(u))."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
        if not directed:
            adj[v].append(u)
    return adj


def build_weighted(edges, directed=True):
    """Dict of lists for sparse or non-integer node ids: {u: [(v, w), ...]}."""
    adj = defaultdict(list)
    for u, v, w in edges:
        adj[u].append((v, w))
        if not directed:
            adj[v].append((u, w))
    return adj


def build_matrix(n, edges, directed=False):
    """Adjacency matrix: O(V^2) space, O(1) edge test. Fine for small dense graphs."""
    m = [[0] * n for _ in range(n)]
    for u, v in edges:
        m[u][v] = 1
        if not directed:
            m[v][u] = 1
    return m


def degrees(adj):
    return [len(nbrs) for nbrs in adj]


def in_degrees(n, adj):
    indeg = [0] * n
    for u in range(n):
        for v in adj[u]:
            indeg[v] += 1
    return indeg


if __name__ == "__main__":
    edges = [(0, 1), (0, 2), (1, 2), (2, 3)]
    adj = build_adjacency(4, edges)
    assert adj == [[1, 2], [0, 2], [0, 1, 3], [2]]
    assert degrees(adj) == [2, 2, 3, 1]
    assert sum(degrees(adj)) == 2 * len(edges)            # handshake lemma
    dadj = build_adjacency(4, edges, directed=True)
    assert dadj == [[1, 2], [2], [3], []]
    assert in_degrees(4, dadj) == [0, 1, 2, 1]
    m = build_matrix(4, edges)
    assert all(m[u][v] == (v in adj[u]) for u in range(4) for v in range(4))
    w = build_weighted([("a", "b", 5), ("b", "c", 2)])
    assert w["a"] == [("b", 5)] and w["c"] == []
    assert build_adjacency(3, []) == [[], [], []]         # isolated nodes still get a list
    print("all tests passed")

List-of-lists, dict-of-lists with weights, and matrix builders, plus degree and in-degree helpers checked with the handshake lemma.

Complexity

Time: O(V + E) build. Space: O(V + E) list, O(V^2) matrix. Use a set per node when fast edge tests are needed in a sparse graph.

By level

Fresher: Builds an adjacency list from an edge list for both directed and undirected graphs. Explains why a matrix is a poor choice for a large sparse graph.

Mid: Compares list, matrix and edge-list representations against the algorithm that will use them. Handles weights, string labels and in-degree computation.

Senior: Discusses CSR arrays for cache-friendly traversal, sharded adjacency storage for very large graphs, and the cost of edge-existence checks at scale. Chooses representations based on the read and update pattern.

Key points

  • Adjacency list is O(V + E) space
  • Undirected edges are stored twice
  • Matrix gives O(1) edge tests at O(V^2) space
  • Weighted edges store (neighbour, weight)
  • Isolated nodes still need entries

Common mistakes

  • Forgetting the reverse edge for undirected graphs
  • Using a matrix for 10^5 nodes
  • Missing isolated nodes in a dict-based list
  • Mixing 0-indexed and 1-indexed labels

Follow-ups

  • How would you store a graph with 10^9 edges that does not fit in memory?
  • What is compressed sparse row (CSR) format?
  • How do you represent a grid as a graph without building edges?

Tips

  • Ask whether the graph is directed and weighted
  • State V and E sizes to justify the choice
  • Mention the handshake lemma for degree sums

Evaluation rubric

  • Correct construction for directed and undirected
  • Correct complexity comparison
  • Handles isolated nodes
  • Justifies the choice