Graphs are one of the most powerful and widely used data structures in computer science. They appear in navigation systems, social networks, recommendation engines, computer networks, and even systems that manage dependencies between tasks. They are also an important topic in coding interviews.
In this chapter, we will understand what graphs are, how they work, the different types of graphs, and how we can represent them in code. We will also explore some important graph concepts that you will use when solving graph problems.
Let's start with a simple example. Imagine we have five cities: A, B, C, D, and E. Some of these cities are connected by direct roads:
If we draw each city as a circle and each road as a line connecting two circles, we get this:
This is a graph. A graph is a data structure that represents a collection of objects and the connections between them. It has two fundamental components.
The first is vertices, also called nodes. Vertices represent the individual objects in our graph. In our example, each city is a vertex.
The second component is edges. Edges represent the connections between vertices. In our example, each road connecting two cities is an edge. So we have five vertices and five edges.
Mathematically, a graph is commonly represented as G = (V, E). Here, V represents the set of vertices, and E represents the set of edges. For our city graph:
That's the basic idea behind graphs. We have objects, and we have relationships connecting those objects. Once we represent a problem this way, we can use graph algorithms to explore those relationships.
We will use this same five-city graph throughout the chapter.
Before we move further, let's understand a few basic terms using our graph of five cities. Each city is a vertex, and each connection between two cities is an edge.
Now, look at City A. It has direct connections to B and C. We call B and C the neighbors, or adjacent vertices, of A. Similarly, City D has three neighbors: B, C, and E.
Notice that A and E are not directly connected. But we can still travel between them by passing through other vertices, for example A → B → D → E.
Another thing to understand is that graphs don't have to follow a particular shape:
A vertex might connect to one other vertex, several vertices, or none at all. And two vertices might be connected through multiple different routes. This flexibility is what makes graphs so useful for modeling real-world systems.
Not all connections work the same way. Some connections go both ways, while others only go in one direction. Based on this, we can divide graphs into two major categories: undirected graphs and directed graphs.
In an undirected graph, an edge represents a connection in both directions. For example, imagine two cities, A and B, connected by a two-way road. If we can travel from A to B, we can also travel from B to A. We represent this with a simple line connecting the two vertices.
In a directed graph, each edge has a specific direction. We use arrows to show which way the connection goes. For example, suppose there's a one-way road from city A to city B. We can travel from A to B, but not from B to A using that same road. So we represent this with an arrow pointing from A to B.
You can also see this difference in social networks:
So whether we use a directed or undirected graph depends on the kind of relationship we want to represent. When you read a graph problem, this is one of the first things to check, because it changes how edges are stored and how traversals behave.
There's another important way we can classify graphs. Some connections have a cost or value associated with them, while others don't.
Let's go back to our city example. Suppose the road between cities A and B is 5 kilometers long, the road between A and C is 12 kilometers long, and the road between B and D is 8 kilometers long. We can represent these distances by writing a number next to each edge. Here is the city graph with a distance on every road:
This gives us what's called a weighted graph. In a weighted graph, each edge has a numerical value associated with it, called its weight. This weight could represent distance, travel time, cost, or any other quantity, depending on the problem. For example, in a navigation system, we might use edge weights to represent how long it takes to travel along each road.
In an unweighted graph, edges don't have individual weights assigned to them. Instead, for many problems, we can treat every edge as having the same cost.
For example, suppose we want to find the minimum number of connections between two people on a social network. Here, we only care about how many connections separate them, not the cost of each connection. So an unweighted graph works well.
In an undirected graph, the degree of a vertex tells us how many edges are connected to it. In our city graph:
In a directed graph, every edge has a direction, so we need to distinguish between two types of degree:
Take Instagram as an example. Suppose three people follow Alice, and Alice follows five other people.
In this directed graph, Alice has an in-degree of 3 because three edges point toward her. She has an out-degree of 5 because five edges point away from her. In-degree counts incoming edges, while out-degree counts outgoing edges.
These concepts become especially useful when we start working with directed graphs, particularly in problems involving relationships and dependencies.
Tip: In an undirected graph, adding up the degrees of all vertices always gives twice the number of edges, because every edge touches two vertices. In our city graph, 2 + 2 + 2 + 3 + 1 = 10 = 2 × 5.
Suppose we want to travel from City A to City E. How can we get there?
If we look at our graph, one possible route is to start at A, travel to B, then D, and finally reach E. We can represent this route as A → B → D → E. This is what we call a path in a graph.
A path is a sequence of vertices where each consecutive pair is connected by an edge.
There's another way to reach City E. Instead of going through B, we could travel from A to C, then D, and finally E: A → C → D → E.
The orange edges form the first path and the green edges form the second. Both use the last edge D → E. So a graph can have multiple paths between the same two vertices.
Which path should we choose? That depends on what we're trying to solve:
Using the weights from the previous section, A → B → D → E costs 5 + 8 + 6 = 19, while A → C → D → E costs 12 + 4 + 6 = 22. Both paths have three edges, but the first one has the lower total weight.
Finding paths is one of the most common problems you'll encounter when working with graphs. Later in this course, we'll explore several algorithms that help us find these paths efficiently.
Suppose we start at City A. We travel from A to B, then B to D, then D to C, and finally from C back to A.
We started at A, traveled through several cities, and returned to A without visiting any other city more than once. This forms what we call a cycle.
A cycle is a closed path that starts and ends at the same vertex, without repeating any other vertex. Cycles can exist in both directed and undirected graphs.
Why are cycles important? Let's consider a practical example. Suppose we have three tasks: A, B, and C.
We have a circular dependency. We can't complete A until B is finished. We can't complete B until C is finished. And we can't complete C until A is finished. So none of these tasks can be completed first.
This is why detecting cycles is so important in systems that deal with dependencies, like build systems, package managers, and task schedulers.
Graphs that don't contain any cycles are called acyclic graphs. When we have a directed graph with no directed cycles, we call it a Directed Acyclic Graph, or DAG for short. In the DAG on the right, Task C has no dependencies, so it can be completed first, then B, then A.
DAGs are especially useful for representing dependencies between tasks. We'll explore them in much more detail when we study topological sorting.
In our original city graph, we can travel from any city to any other city by following some sequence of roads. In other words, every city is reachable from every other city. When this happens, we say the graph is connected.
Now suppose we remove the road between cities D and E. City E becomes completely isolated. There's no longer any path connecting E to the other four cities. So our graph is now disconnected.
This brings us to another useful concept called a connected component. In an undirected graph, a connected component is a group of vertices where every vertex is reachable from every other vertex in that group.
In our example, we now have two connected components. The first contains cities A, B, C, and D. The second contains only City E. A connected graph has exactly one connected component.
This concept is especially useful when we're working with networks. For example, we might want to identify isolated groups of computers, find separate communities in a social network, or simply determine whether two vertices are connected.
Connectivity works a little differently in directed graphs because the direction of edges also matters. We'll explore that distinction later in the course.
If you've already studied trees, you might have noticed that graphs look somewhat familiar. That's because a tree is actually a special type of graph.
More specifically, a tree is an undirected graph that is connected and contains no cycles:
Our city graph is connected, but it is not a tree, because it contains the cycle A → B → D → C → A. If we remove the edge between C and D, the cycle disappears and we get a tree:
Trees have a couple of interesting properties:
General graphs don't have these restrictions. They can contain cycles, have multiple paths between the same vertices, and even consist of disconnected components.
So, every tree is a graph, but not every graph is a tree. Because trees are a special type of graph, many of the concepts and techniques you've already learned for trees will come in handy when we start working with graphs.
So far, we've been representing graphs using circles and lines. But how do we actually store a graph in code? There are two common ways to do this: the adjacency list and the adjacency matrix.
Let's start with the adjacency list. The idea is simple: for each vertex, we maintain a list of all the vertices it's directly connected to. Here is the adjacency list for our city graph:
A has two neighbors, B and C. D has three neighbors, B, C, and E.
Since our graph is undirected, every edge appears in the lists of both vertices it connects. For example, B appears in A's list, and A appears in B's list. That's because we can travel in both directions. This is why the five edges produce ten entries in total.
In a directed graph, we typically store only the outgoing neighbors. So if there's an edge from A to B, we add B to A's list, but not the other way around unless that edge also exists.
In code, we can implement an adjacency list using an array of lists or a hash map that maps each vertex to its neighbors. The array version works well when vertices are numbered 0 to V − 1. The hash map version is handy when vertices have names, like cities or user IDs.
The code below builds the adjacency list for our city graph using an array of lists. The cities are numbered A = 0, B = 1, C = 2, D = 3, E = 4. For a directed graph, you would remove the second line inside the loop, so each edge is added only to its starting vertex.
One of the biggest advantages of an adjacency list is that it saves memory. For a graph with V vertices and E edges, it requires O(V + E) space. This makes it a great choice for sparse graphs, where we have relatively few edges compared to the number of possible connections.
It's also very convenient when we want to visit all the neighbors of a particular vertex. Visiting the neighbors of a vertex u takes time proportional to the number of its neighbors, which is exactly what graph traversals need. The downside is that checking whether one specific edge (u, v) exists means scanning u's list.
The second common way to represent a graph is using an adjacency matrix. Instead of storing a list of neighbors for each vertex, we use a two-dimensional matrix.
If our graph has V vertices, the matrix has V rows and V columns. Each row and column represents a vertex. For an unweighted graph, we store either 0 or 1 in each cell. A value of 1 means there's an edge between the two vertices, and a value of 0 means there's no edge.
Here is the adjacency matrix for our city graph:
Since A and B are directly connected, the cell at row A and column B contains 1. But A and E aren't directly connected, so that cell contains 0.
In an undirected graph, the adjacency matrix is always symmetric along its diagonal. That's because if A is connected to B, then B is also connected to A. In a directed graph, the matrix is usually not symmetric. For a weighted graph, we store the weight in the cell instead of 1.
The code below builds the adjacency matrix for our city graph, again with A = 0 through E = 4:
One major advantage of an adjacency matrix is that checking whether an edge exists takes constant time. We simply look up the corresponding cell.
But there's a trade-off. An adjacency matrix always requires O(V²) space, regardless of how many edges actually exist. Even if our graph has only a few edges, we still need space for every possible pair of vertices. Our city graph uses only 10 of the 25 cells. Visiting the neighbors of a vertex also takes O(V) time, because we have to scan its entire row.
So adjacency matrices are useful for smaller or dense graphs, where many vertices are connected. Adjacency lists are generally a better choice for large, sparse graphs, where relatively few connections exist.
Most graph problems in coding interviews use an adjacency list, because most real graphs are sparse and most algorithms spend their time visiting neighbors.
Now that we know how to represent graphs, let's look at one of the most important operations we can perform on them: graph traversal. Graph traversal means visiting the vertices of a graph in a systematic way. There are two fundamental algorithms for this: Breadth-First Search and Depth-First Search.
BFS explores a graph one level at a time. We start at a vertex and first explore all its immediate neighbors. Then we move on to the neighbors of those vertices. We keep expanding outward until we've visited everything reachable.
To keep track of which vertex to explore next, BFS uses a queue. Starting from A in our city graph (visiting neighbors in alphabetical order), BFS visits:
The level of each vertex is the fewest number of edges needed to reach it from A. That is why one of the most useful applications of BFS is finding the shortest path in an unweighted graph.
DFS works a little differently. Instead of exploring all nearby vertices first, it picks one path and follows it as far as possible. Once it reaches a point where there's nowhere new to go, it backtracks and tries another path.
Starting from A, DFS goes A → B → D → E. At E there's nowhere new to go, so it backtracks to D and takes the remaining edge to C:
DFS can be implemented using recursion or an explicit stack.
Both algorithms keep track of the vertices they have already visited, so no vertex is processed twice. When we use an adjacency list, both have a time complexity of O(V + E), because each vertex and each edge is handled a constant number of times. With an adjacency matrix, the same traversals take O(V²), because finding the neighbors of each vertex means scanning a full row.
These two algorithms form the foundation of many graph problems, including finding paths, checking connectivity, detecting cycles, and much more. We'll explore both algorithms in detail in the upcoming lessons.
Now that we've covered the basics, let's look at how graphs are used in the real world. Many applications rely on them:
Dependency management is a particularly important application. Suppose you're building a software project where certain modules depend on other modules. We can represent each module as a vertex and each dependency as a directed edge. Then, using graph algorithms, we can figure out the correct order in which to build those modules.
Not every graph problem looks like a graph problem. For example, imagine a two-dimensional grid where you can move up, down, left, or right. We can treat each valid cell as a vertex and every allowed movement as an edge. With that, finding a path through a maze becomes a graph traversal problem.
Here is a small 3 × 3 maze. S is the start, G is the goal, and # is a wall:
Each open cell becomes a vertex, labeled by its row and column, and each move between two open neighboring cells becomes an edge:
A BFS from S now finds the shortest way through the maze: S → (0,1) → (0,2) → (1,2) → G, which takes four moves.
This is an important skill to develop for coding interviews. Often, the hardest part isn't writing the graph algorithm itself. It's recognizing that the problem can be represented as a graph in the first place.
10 quizzes