Quick Answer
Graph data structure stores nodes joined by edges. Edges show how things connect. This post stores a graph in 2 ways. They are an adjacency list and an adjacency matrix. List space is O(n + e). Matrix space is O(n squared). Python and C++ code below was executed.
Graphs sound abstract and mathematical. Yet a map of cities and roads is already a graph. Real question is how to store a graph data structure in code.
Sections below store one small graph data structure in 2 ways and compare them with tested numbers.
What Is a Graph Data Structure?
Graph data structure means a set of points with connections between them. Points are called nodes or vertices. Connections are called edges.
Picture 4 cities on a map. Every city is a node and every road between 2 cities is an edge. Cities plus the roads that join them make the graph.
Arrays line items up in a row. Graphs let any item connect to any other item in any pattern. See the graph lesson and the what is DSA guide for the wider path.
What Are the Types of Graphs?
- Undirected graph. Edges go both ways like a two way road.
- Directed graph. Edges point one way like a one way street.
- Unweighted graph. Every edge counts the same.
- Weighted graph. Edges carry a number like the distance between 2 cities.
How Do You Store a Graph Data Structure?
Computers need a concrete layout. Examples below use one undirected graph with 4 nodes numbered 0 to 3. Edges are 0 to 1, 0 to 2, 1 to 2 and 2 to 3.
Approach #1: Adjacency List
What you get. Every node stores a list of its neighbors. Only edges that exist take space.
class Graph:
def __init__(self, directed=False):
self.adj = {}
self.directed = directed
def add_edge(self, u, v):
self.adj.setdefault(u, []).append(v)
self.adj.setdefault(v, [])
if not self.directed:
self.adj[v].append(u)
def neighbors(self, node):
return self.adj.get(node, [])
def has_edge(self, u, v):
return v in self.adj.get(u, [])
graph = Graph()
for u, v in [(0, 1), (0, 2), (1, 2), (2, 3)]:
graph.add_edge(u, v)
for node in range(4):
print(node, graph.neighbors(node))
print(graph.has_edge(0, 2), graph.has_edge(0, 3))
Output is 0 [1, 2] then 1 [0, 2] then 2 [0, 1, 3] then 3 [2]. Next line is True False because 0 and 2 share an edge and 0 and 3 do not. Setting directed=True skips the second link.
Approach #2: Adjacency Matrix
What you get. Grid with one row and one column per node. Cells are 1 when 2 nodes share an edge and 0 when they do not.
| Node | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 0 |
| 1 | 1 | 0 | 1 | 0 |
| 2 | 1 | 1 | 0 | 1 |
| 3 | 0 | 0 | 1 | 0 |
Grid is symmetric across the diagonal because the graph is undirected. If 0 connects to 2 then 2 connects to 0 so both cells show 1.
n = 4
matrix = [[0] * n for _ in range(n)]
for u, v in [(0, 1), (0, 2), (1, 2), (2, 3)]:
matrix[u][v] = 1
matrix[v][u] = 1
for row in matrix:
print(row)
print(matrix[0][2] == 1, matrix[0][3] == 1)
Output is the 4 rows from the table and then True False. C++ version stores both layouts for the same edges.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 4;
vector<vector<int>> adj(n);
vector<vector<int>> matrix(n, vector<int>(n, 0));
int edges[4][2] = {{0, 1}, {0, 2}, {1, 2}, {2, 3}};
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
matrix[e[0]][e[1]] = 1;
matrix[e[1]][e[0]] = 1;
}
for (int node = 0; node < n; node++) {
cout << node << " ->";
for (int next : adj[node]) cout << " " << next;
cout << endl;
}
for (auto& row : matrix) {
for (int cell : row) cout << cell << " ";
cout << endl;
}
}
It prints the 4 neighbor lines and then the 4 matrix rows. Code uses vector so the size is not fixed.
Tested. Python 3.13.18 compared both layouts on 300 random graphs and agreed on every pair of nodes. g++ 13.3 compiled the C++ version with warnings on. Tests ran in a cloud sandbox.
Which Layout Wins for a Graph Data Structure?
Call the node count n and the edge count e. Lists need O(n + e) space because they store every node once and every edge once. Matrices need O(n squared) space because they reserve a cell for every possible pair.
Test below used 2,000 nodes and 10,000 random edges. Table lists memory from Python's tracemalloc.
| Point | Adjacency list | Adjacency matrix |
|---|---|---|
| Stored entries | 20,000 | 4,000,000 |
| Memory | 0.40 MB | 32.13 MB |
| Edge check for 2 nodes | 141 ns (23 neighbors) | 23 ns |
| Space formula | O(n + e) | O(n squared) |
Matrix edge check is O(1) while list edge check scans the neighbors so it costs O(degree). Matrix wins when a graph data structure is small or nearly full. List wins when edges are few.
Scale shows the gap. Networks of 1,000,000 users with about 200 friends per user need a trillion matrix cells.
Lists need about 200 million entries. Numbers here are arithmetic and not a measurement.
Where Are Graphs Used in Real Software?
Maps treat every junction as a node and every road as a weighted edge. Then they search for the shortest path. Social networks store people as nodes and friendships as edges.
Web pages are nodes and links are edges. Moving through a graph data structure needs a search like breadth first search or depth first search. Depth first search uses a stack to remember where to go next as the stack data structure post shows.
Practice the pattern in the graph practice set and open the graph traversal visualiser to watch a search move.
Frequently Asked Questions
How Do a Node and an Edge Differ?
Nodes are single points like a city or a person. Edges are connections between 2 nodes like a road or a friendship. Graphs are nodes plus edges.
How Do the 2 Storage Layouts Differ?
Adjacency lists store the neighbors of every node. Matrices are grids that mark every pair as connected or not. Lists save space and matrices check an edge in O(1).
When Should You Use an Adjacency List?
Use it when the graph has few edges compared with the maximum possible. In the 2,000 node test the list used 0.40 MB against 32.13 MB for the matrix.
How Do Directed and Undirected Graphs Differ?
Undirected edges work both ways like a mutual friendship. Directed edges point one way like a follow that is not returned.
What Is a Weighted Graph?
Weighted graphs give every edge a number like distance or cost. Maps use weights to find the shortest or cheapest route and not just any route.
Are Trees a Type of Graph?
Yes. Trees are connected graphs with no cycles. Every tree is a graph but not every graph is a tree.
How Does an Undirected Graph Store One Edge?
It stores the edge in both directions. Lists add both nodes to one another's lists and matrices set 2 cells to 1. That is why the matrix is symmetric.
What Should You Remember About the Graph Data Structure?
Every graph data structure models some set of connections. Real skill is choosing how to store them.
Key takeaways.
- List space is O(n + e) and matrix space is O(n squared).
- Matrix edge checks are O(1) and list edge checks scan the neighbors.
- Undirected edges are stored in both directions.
Check yourself. Add an edge between nodes 1 and 3. Which lists gain an entry and which 2 matrix cells become 1? Answer is list 1 gains 3 and list 3 gains 1 while cells (1, 3) and (3, 1) become 1.