Graphs for Coding Interviews: A Crash Course
Graphs model anything made of things and the connections between them: cities and roads, people and friendships, tasks and dependencies.
- The definition
A graph G is a pair (V, E). V is a set of vertices, also called nodes, and E is a set of edges that connect pairs of vertices.
- Vocabulary
You will see these words in almost every graph problem statement.
- Vertex
- Edge
- Directed and undirected
- Indegree and outdegree
- Connected and disconnected
- Kinds of graphs
Problems often hint at the kind of graph they use.
Directed or undirected, cyclic or acyclic, weighted or unweighted: each changes which algorithm fits.
- How graphs are given
Interviewers rarely hand you a ready made graph object. Instead you get an array of edges, an adjacency list, an adjacency matrix or a grid. Your first job is usually to turn that input into an adjacency list.
Once you have an adjacency list, depth first search and breadth first search work the same way no matter how the graph was given.