Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Graphs and connections
EXPERIMENT 36 / 66

Choose how to store the connections.

Distinguish directed edges, weights, and representation costs before choosing an algorithm.

BY NAVAN SAMI◷ 8 MIN READCORESTRUCTURE

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 THING THAT MUST STAY TRUE

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.

the_strategy.txt
DEFINE all vertices
ADD directed or reciprocal edges deliberately
CHOOSE storage based on density and needed operations

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

graph_representations.py
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])
↳ EXPECTED OUTPUT
{'A': ['B'], 'B': ['C'], 'C': []}
[0, 1, 0]
  1. 1

    This graph is directed. Adding A→B does not automatically add B→A. An undirected representation should record both directions consistently.

  2. 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. 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

TIME

O(V + E) list construction; O(V² + E) matrix construction

SPACE

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

A SMALL MISSION

Build an undirected adjacency list from one edge and verify both directions.

Reveal one possible solution +
one_possible_solution.py
graph = {"A": [], "B": [], "C": []}
for u, v in [("A", "B")]: graph[u].append(v); graph[v].append(u)
print(graph)

06 Check your reasoning

QUICK SIGNAL CHECK

What does a directed edge A→B guarantee?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.