Graphs

Points and connections · Part of Trees and graphs

Key idea

Practice

6 questions · about 3 min

Explained step by step

Graph

A graph is a nonlinear structure made of vertices, the points, and edges, the lines joining them. It's written as a set of vertices V and a set of edges E. For example, 5 vertices numbered 1 to 5 and 7 edges like (1, 2) or (2, 4). You can think of it as a linked list where each node can point to any number of others, and a tree is a special case of a graph.

Some graph terms. 2 vertices are adjacent if an edge joins them. A path is a sequence of edges taking you from one vertex to another, like 1-5-2-4. A vertex's degree is how many edges it has. In a directed graph, the in-degree, edges arriving, is distinguished from the out-degree, edges leaving.

Many real systems are modeled as graphs. In a social network, users are vertices and friendships, edges. On a map, intersections are vertices and streets, edges. In the subway, stations and tracks. And problems become questions about the graph: recommending friends is looking for friends of friends, and finding the fastest route is looking for the lowest-weight path.

Directed graph

There are 3 ways to classify a graph. By direction: in an undirected one, each edge goes both ways, like a friendship; in a directed one, A → B doesn't imply B → A, like following someone. By connection: in a connected one you can reach any vertex from any other; in a disconnected one, some vertices can't be reached. And by weight: in a weighted one, each edge has a number, like a distance or a time.

Adjacency matrix

An adjacency matrix stores a graph of n vertices in an n × n table. Row i and column j say whether there's an edge between vertex i and vertex j: 1 if there is, 0 if not. In an undirected graph, the table is symmetric about the diagonal. With weights, the weight is stored instead of 1. Checking, adding or removing an edge is O(1), but it takes O(n²) memory.

Adjacency list

An adjacency list stores, for each vertex, the list of its neighbors. It only stores edges that exist, so it takes O(n + m), with m the number of edges, which is usually much less than n². Checking whether an edge exists means walking a vertex's list, slower than the matrix. It resembles a hash table's separate chaining, and can be improved the same way: swapping the lists for hash tables or trees.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Points and connections