Builds onHash map lookup
01The idea
A graph is a set of nodes joined by edges. Roads between cities, friendships between people and links between web pages are all graphs. A tree is a special graph with no loops.
Edges can have a direction. In an undirected graph, an edge between a and b works both ways. In a directed graph, an edge from a to b only lets you go from a to b. Edges can also carry a weight, such as a distance or a cost.
Problems hand you the graph as an edge list, such as [[0, 1], [1, 2]]. An edge list is hard to search. To find the neighbours of one node, you would scan every edge. So the first step is to build an adjacency list. It has one list per node, holding the nodes that node connects to.
adj[0] = [1, 2] means node 0 has edges to 1 and 2
With an adjacency list, "who is next to x?" is adj[x]. Every graph search you learn later starts from it.
There is a second way to store a graph, the adjacency matrix. It is an n by n grid where matrix[a][b] is 1 when there is an edge. It answers "is there an edge from a to b?" in O(1), but it takes O(n²) space even when there are few edges. For most interview problems, the adjacency list is the right choice.
02How to spot it
The problem is a graph problem when:
- it gives you pairs that connect things: edges, roads, prerequisites, friendships, flights
- it asks whether you can get from one thing to another, or how many steps it takes
- it asks about groups that are connected, or about cycles
Some graphs are hidden. A grid is a graph where each cell connects to the cells above, below, left and right. Words can be nodes that connect when they differ by one letter. You do not have to build these graphs. Work out the neighbours of a node when you need them.
Check two things before you build anything. Is the graph directed? Are the nodes numbered 0 to n - 1, or named by strings? Use a list of lists for numbers, and a dictionary of lists for strings.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue