Choose how to store the connections.
Distinguish directed edges, weights, and representation costs before choosing an algorithm.
01 Model the idea
A graph model begins with meaning: what is a vertex, what does an edge allow, is the connection directed, and does it have a cost? An adjacency list stores only described neighbours; a matrix reserves one cell per possible vertex pair. Lists often suit sparse graphs, while matrices make direct edge lookup simple at a quadratic storage cost.
The representation preserves the graph’s direction and edge meaning.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
DEFINE all vertices
ADD directed or reciprocal edges deliberately
CHOOSE storage based on density and needed operations03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
vertices = ["A", "B", "C"]
edges = [("A", "B"), ("B", "C")]
adjacency = {vertex: [] for vertex in vertices}
positions = {vertex: i for i, vertex in enumerate(vertices)}
matrix = [[0] * len(vertices) for _ in vertices]
for start, end in edges:
adjacency[start].append(end)
matrix[positions[start]][positions[end]] = 1
print(adjacency)
print(matrix[0]){'A': ['B'], 'B': ['C'], 'C': []}
[0, 1, 0]- 1
This graph is directed. Adding A→B does not automatically add B→A. An undirected representation should record both directions consistently.
- 2
The matrix has V² cells even when E is small. An adjacency list has O(V+E) storage when every vertex is represented.
- 3
A weighted matrix needs a distinct representation for no edge if zero-cost edges are legal. A zero cannot mean both zero cost and no connection without ambiguity.
04 Count the cost
O(V + E) list construction; O(V² + E) matrix construction
O(V + E) list or O(V²) matrix
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Build an undirected adjacency list from one edge and verify both directions.
Reveal one possible solution +
graph = {"A": [], "B": [], "C": []}
for u, v in [("A", "B")]: graph[u].append(v); graph[v].append(u)
print(graph)06 Check your reasoning
What does a directed edge A→B guarantee?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.