Lesson 2 · Unit 01
List or matrix
Two ways to store a graph, and what each costs
What you practise
- Space and lookup trade-offs
- Weights
Try a question from this lesson
Pick one
A network has 1,000,000 users. You store one yes/no cell for every possible pair of users: "are they friends?". How many cells is that?
Correct answer
1 trillion
Why
A row and a column per user gives 1,000,000 × 1,000,000 = a trillion cells, nearly all "no". If people have about 200 friends each, a list of real friendships needs only about 200 million entries.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The adjacency matrix
A matrix stores a graph as a V × V grid: m[a][b] is 1 when there is an edge from a to b.
Asking "is there an edge?" is a single lookup, O(1). The price is O(V²) memory, even when the graph has almost no edges.
m = [
[0, 1, 1], # row 0
[1, 0, 0], # row 1
[1, 0, 0], # row 2
]
print(m[0][2]) # 1: edge 0-2
print(m[1][2]) # 0: no edgeconst m = [
[0, 1, 1], // row 0
[1, 0, 0], // row 1
[1, 0, 0], // row 2
];
console.log(m[0][2]); // 1: edge 0-2
console.log(m[1][2]); // 0: no edgeconst m: number[][] = [
[0, 1, 1], // row 0
[1, 0, 0], // row 1
[1, 0, 0], // row 2
];
console.log(m[0][2]); // 1: edge 0-2
console.log(m[1][2]); // 0: no edgeConcept
Weighted edges
Edges can carry a number: a distance, a price, a delay. That is a weighted graph.
In an adjacency list, store pairs of (neighbour, weight). In a matrix, store the weight in the cell.
roads = {
"home": [("shop", 4), ("gym", 9)],
"shop": [("gym", 2)],
"gym": [],
}
for place, km in roads["home"]:
print(place, km)const roads = {
home: [["shop", 4], ["gym", 9]],
shop: [["gym", 2]],
gym: [],
};
for (const [place, km] of roads.home) {
console.log(place, km);
}type Road = [string, number];
const roads: Record<string, Road[]> = {
home: [["shop", 4], ["gym", 9]],
shop: [["gym", 2]],
gym: [],
};
for (const [place, km] of roads.home) {
console.log(place, km);
}TypeScript note[string, number] is a tuple type: exactly two items, a string then a number. A plain (string | number)[] would forget which is which.
8 more exercises in the app
- 3× type the answer
- 2× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.