Knowledge / Computer Science and Engineering / Graphs and their representation

Graphs and their representation

Computer Science and Engineering (B.E./B.Tech) · Data structures · free study notes for exams, placements and interviews

In short

A graph G = (V, E) is a set of vertices joined by edges, and it is the general data structure from which lists, trees and networks are special cases. Choosing its representation - adjacency matrix, adjacency list, edge list or CSR - decides the memory and the running time of every algorithm built on top of it, so representation is examined as heavily as the algorithms. GATE CS/DA tests graph terminology, degree and edge counting, matrix powers, traversal order and representation complexity almost every year; AICTE/CBCS "Data Structures" and "Design and Analysis of Algorithms" papers ask the representations with diagrams. In placement rounds (TCS NQT, Infosys, Amazon, Flipkart, Microsoft India, Zoho, Oracle, Samsung R&D) most medium-hard coding questions are graph questions in disguise - grids, dependencies, networks, friend suggestions.

Explained

Definitions and terminology

Types and classification

Adjacency matrix

Adjacency list, edge list, incidence matrix and CSR

Traversals on a representation

Choosing a representation, and syllabus notes

Key points

Formulas and examples

Handshaking: Σ_{v∈V} deg(v) = 2E (deg in edges; a self-loop counts 2)
Digraph: Σ in-deg(v) = Σ out-deg(v) = E
Max edges, simple undirected: E_max = n(n−1)/2; simple directed: n(n−1); K_{m,n}: mn
Density D = 2E / (n(n−1)) for undirected, E / (n(n−1)) for directed (dimensionless, 0 to 1)
Space: matrix = Θ(V²) cells; adjacency list = Θ(V + 2E) undirected, Θ(V + E) directed; edge list = Θ(E); incidence matrix = Θ(V·E)
Walks: number of walks of length k from i to j = (Ak)[i][j], A = adjacency matrix
Tree: E = V − 1; forest with c components: E = V − c; connected graph needs E ≥ V − 1
Any simple graph with E > (n−1)(n−2)/2 is connected; labelled simple graphs on n vertices = 2n(n−1)/2
Planar (n ≥ 3): V − E + F = 2 and E ≤ 3V − 6; bipartite planar: E ≤ 2V − 4
Spanning trees of Kₙ (Cayley) = nn−2

Example 1 - memory, matrix vs list vs CSR (sparse graph). An Indian road network model has n = 10,000 junctions and E = 50,000 undirected road segments (4-byte vertex ids, 8-byte pointers).

Example 2 - degree counting. (a) A graph has degree sequence 3, 3, 3, 3, 2, 2, 2. Σ deg = 12 + 6 = 18, so E = 18/2 = 9 edges. (b) Can a simple graph have 5 vertices each of degree 3? Σ deg = 15, which is odd, so no - the handshaking lemma forbids an odd degree sum. (c) A 4-regular graph with 10 vertices: E = (10 × 4)/2 = 20 edges, against E_max = 10 × 9/2 = 45. (d) With n = 10, any simple graph having more than (9 × 8)/2 = 36 edges - i.e. 37 or more - is necessarily connected.

Example 3 - matrix powers. C₄ with edges 1-2, 2-3, 3-4, 4-1:

1234
10101
21010
30101
41010

A²[1][1] = (0,1,0,1)·(0,1,0,1) = 2; A²[1][3] = (0,1,0,1)·(0,1,0,1) = 2; A²[1][2] = (0,1,0,1)·(1,0,1,0) = 0. So A² = [[2,0,2,0],[0,2,0,2],[2,0,2,0],[0,2,0,2]]. Reading it: 2 walks of length 2 from 1 to 3 (1-2-3 and 1-4-3), none of length 2 from 1 to 2 (odd/even parity - the graph is bipartite), and trace(A²) = 2 + 2 + 2 + 2 = 8 = 2E with E = 4. ✓

Example 4 - BFS and DFS trace. Undirected graph, neighbours stored in alphabetical order: A: B, C | B: A, D | C: A, D, E | D: B, C, F | E: C, F | F: D, E.

Example 5 - Kahn's topological sort. DAG of prerequisites: 1→2, 1→3, 2→4, 3→4, 3→6, 4→5, 6→5. In-degrees: 1:0, 2:1, 3:1, 4:2, 5:2, 6:1.

  1. Output 1 → in-deg(2)=0, in-deg(3)=0.
  2. Output 2 → in-deg(4)=1. 3. Output 3 → in-deg(4)=0, in-deg(6)=0.
  3. Output 4 → in-deg(5)=1. 5. Output 6 → in-deg(5)=0. 6. Output 5.

Order = 1, 2, 3, 4, 6, 5 (6 of 6 vertices output ⇒ acyclic). Adding edge 5→1 would leave every in-degree ≥ 1 after step 0, output 0 vertices, and so report a cycle.

Example 6 - which representation. Dijkstra on a Metro-style network with V = 10⁵, E = 2×10⁵: matrix version ≈ V² = 10¹⁰ basic steps (minutes to hours, and 10¹⁰ cells of memory - infeasible); heap + adjacency list ≈ (V + E) log₂V = 3×10⁵ × 16.6 ≈ 5×10⁶ steps (milliseconds).

OperationAdjacency matrixAdjacency listAdjacency set/mapEdge list
SpaceΘ(V²)Θ(V+E)Θ(V+E)Θ(E)
Add edgeO(1)O(1)O(1) avgO(1)
Delete edge (u,v)O(1)O(deg u)O(1) avgO(E)
Is u-v an edge?O(1)O(deg u)O(1) avgO(E)
List neighbours of uO(V)O(deg u)O(deg u)O(E)
BFS / DFS allO(V²)O(V+E)O(V+E)O(V·E)
Best fordense, V ≤ ~10³sparse, generalmany edge queriesKruskal, input/IO
// adjacency list (weighted, 0-indexed) and CSR build in C++
int n, m;  cin >> n >> m;
vector<vector<pair<int,int>>> adj(n);
vector<array<int,3>> edges(m);
for (auto &e : edges) {                       // read edge list once
    cin >> e[0] >> e[1] >> e[2];              // u, v, w
    adj[e[0]].push_back({e[1], e[2]});
    adj[e[1]].push_back({e[0], e[2]});        // drop this line for a digraph
}
vector<int> head(n + 1, 0), to(2 * m);        // CSR: counting sort of degrees
for (auto &e : edges) { head[e[0] + 1]++; head[e[1] + 1]++; }
for (int v = 0; v < n; ++v) head[v + 1] += head[v];
// fill 'to' using a copy of head as write cursors; neighbours of v are
// to[head[v] .. head[v+1]-1]
# BFS shortest hops on an adjacency list (dict of lists)
from collections import deque
def bfs(adj, src, n):
    dist, par = [-1] * n, [-1] * n
    dist[src] = 0
    q = deque([src])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if dist[v] == -1:          # mark on enqueue
                dist[v], par[v] = dist[u] + 1, u
                q.append(v)
    return dist, par

Where it is used

Interview questions

Common mistakes

Related topics

Open in the Knowledge reader →Find jobs →