Home
Day 1 · Week 1

Graph Representation

Level 1 · Fundamentals  ·  2 hrs: ~45 min theory · ~60 min code · ~15 min notes

🧠 Mental Model

A graph is just "things (nodes) and the relationships between them (edges)." Everything else — the matrix, the list, the arrays — is only a choice of how to store those relationships in memory. Pick the storage that makes your most frequent operation cheap.

The single question that drives the choice: "What do I ask most often?"

⚙️ The Three Representations

1. Adjacency List (the interview default)

Each node stores a list of its neighbors. For n nodes you keep n lists. This is what you'll use in ~90% of interview problems because most graphs are sparse (edges ≪ n²).

2. Adjacency Matrix

An n × n grid where matrix[u][v] = 1 (or the weight) if an edge exists. Instant edge lookups, but costs O(n²) space even if the graph has 3 edges. Great for dense graphs or Floyd-Warshall (Week 2).

3. Edge List

Just a list of (u, v, weight) triples. Minimal, and perfect when the algorithm processes edges directly (Kruskal's, Bellman-Ford).

Directed vs Undirected · Weighted vs Unweighted

📊 Complexity & When to Use

RepresentationSpaceEdge lookupIterate neighborsBest for
Adjacency ListO(V + E)O(deg)O(deg) — optimalSparse graphs (default)
Adjacency MatrixO(V²)O(1)O(V)Dense graphs, Floyd-Warshall
Edge ListO(E)O(E)O(E)Kruskal, Bellman-Ford
Rule of thumb: If the problem gives you a grid, it's an implicit adjacency list — each cell's neighbors are up/down/left/right. You rarely build an explicit graph for grids.

💻 Reference Implementation (Java)

A flexible Graph class backed by an adjacency list, supporting directed/undirected and weighted edges.

import java.util.*;

/** Weighted adjacency-list graph. Set weighted=false to ignore weights. */
public class Graph {
    private final int n;
    private final boolean directed;
    private final List<int[]>[] adj;   // adj[u] = list of {neighbor, weight}

    public Graph(int n, boolean directed) {
        this.n = n;
        this.directed = directed;
        adj = new List[n];
        for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
    }

    public void addEdge(int u, int v, int w) {
        adj[u].add(new int[]{v, w});
        if (!directed) adj[v].add(new int[]{u, w}); // undirected → both ways
    }

    public void addEdge(int u, int v) { addEdge(u, v, 1); } // unweighted default

    public List<int[]> neighbors(int u) { return adj[u]; }

    public int size() { return n; }
}

// --- Adjacency matrix, when you need O(1) edge lookups ---
int[][] matrix = new int[n][n];
matrix[u][v] = w;                 // directed
// matrix[v][u] = w;             // add this line for undirected

⚠️ Common Pitfalls

Undirected forgetfulness: adding u→v but not v→u. Half your traversal silently breaks.
0- vs 1-indexed nodes: problems often label nodes 1..n. Size your arrays n+1 or subtract 1 consistently.
Matrix on huge n: n = 10⁵ means a 10¹⁰-cell matrix — instant memory limit exceeded. Default to lists.

🎭 Problem Variances — how representation choice is tested

Representation is rarely the whole question, but the right choice quietly decides whether you pass or TLE. Interviewers probe it via:

Disguise / phrasingWhat's really testedTwist to handle
"n up to 10⁵, edges sparse"Will you pick a list over a matrix?Matrix = 10¹⁰ cells → MLE. Must use adjacency list
"Frequent 'is there an edge u–v?' queries"O(1) lookup needAdjacency matrix or a HashSet of edges
"Grid / maze / islands"Implicit graph recognitionCells = nodes, 4/8-dir = edges; don't build explicit graph
"Edges given as a list, process by weight"Edge-list fitKeep as edge list (Kruskal, Bellman-Ford)
"Nodes labeled 1..n" / string node IDsIndexing hygieneSize arrays n+1, or map strings → ints consistently
"Convert / model this real-world thing as a graph"Modeling skillIdentify what's a node vs an edge before coding
Recognition heuristic: before coding, state out loud "nodes are ___, edges are ___, I'll store it as ___ because ___." That one sentence signals maturity to interviewers.

🎯 Problems

LC 1791 Find Center of Star Graph Warmup — degree counting on an edge list. Easy
LC 997 Find the Town Judge Model in-degree vs out-degree; pure representation reasoning. Easy
LC 1971 Find if Path Exists in Graph Build adjacency list, then a simple traversal — bridges into Day 2/3. Easy