Practise Graphs one question at a time. Answer out loud or in writing, get graded, and see exactly what you missed.
What is a graph, and what real-world problems does it model?
A graph is a set of objects plus the relationships between them. The objects become nodes, and each relationship becomes an edge joining two of them. Whenever a problem is about connections, a graph is the natural fit.
Real-world examples include:
- Road maps, where intersections connect by streets
- Social networks, where people connect by friendship
- The web, where pages connect by hyperlinks
- Task schedules, where jobs connect by "must run before"
The payoff is that the same algorithms work on all of these. Questions like "can this node reach that one" or "what is the cheapest route" become the same search over any of them. That reuse is why graphs show up in routing, package managers and recommendation systems.
Missed:
“An adjacency list stores, for each vertex, a list of the vertices it connects to. An adjacency matrix is a V by V grid where the cell at row i, column j says whether there's an edge between those two vertices. I'd usually go with the list because it only takes O(V + E) space, while the matrix always takes O(V^2), so the list wins for sparse graphs, which is most real ones.”
Knew itThey have both structures right and the space tradeoff. They skip that a matrix answers edge-existence checks in O(1) versus a scan on a list, which is the usual reason to pick a matrix at all.
Missed: Doesn't mention that a matrix checks whether a specific edge exists in O(1), while a list needs a scan - this is the main reason to use a matrix.
Get your own answers graded
Sign up free. Your account comes with 50 credits for grading, and it remembers what you missed.
What it covers
All 60 questions
Graph basics and terminology
What a graph models: vertices, edges, degree, direction, weights, paths, cycles and connectivity, and how to model a real network such as a social graph.
- What is a graph, and what real-world problems does it model?
- What are vertices, edges, degree, and neighbors in a graph?
- How do directed and undirected graphs differ, and when do you use each?
- What does it mean for a graph to be weighted, and why does it matter?
- What is a path, a cycle, and a connected graph? Pro
- How would you model a social network as a graph? Pro
Graph representations
Adjacency lists, adjacency matrices and compressed sparse row: what each costs in memory, lookup speed and cache behavior.
- How do an adjacency list and an adjacency matrix store a graph?
- When is an adjacency matrix worth its memory cost over a list? Pro
- Which representation makes checking if an edge exists fast, and why? Pro
- What is compressed sparse row, and why does it beat adjacency lists? Pro
- How does pointer chasing in adjacency lists hurt cache performance? Pro
BFS and DFS traversal
How breadth-first and depth-first search work, what they cost, when to pick each, how to track visited nodes and how to walk grids.
- How does breadth-first search explore a graph, step by step?
- How does depth-first search explore a graph, step by step?
- When should you use BFS versus DFS on a graph?
- What do BFS and DFS cost in time and space, and why? Pro
- Why can recursive DFS crash where an iterative DFS does not? Pro
- Why must you track visited nodes, and what breaks without it? Pro
- How do you model a grid or maze as a graph? Pro
- How do you choose between a visited array and a hash set? Pro
Cycles and topological sort
Finding cycles, ordering DAGs with Kahn's algorithm or DFS, and scheduling tasks that depend on each other.
- What is a topological sort, and when do you need one? Pro
- How do you detect a cycle in a graph? Pro
- How do Kahn's algorithm and DFS-based topological sort differ? Pro
- How does topological sort reveal whether a graph has a cycle? Pro
- How do you model task dependencies as a graph to schedule them? Pro
- How would you stream a topological order without loading everything? Pro
Connectivity and union-find
Connected and strongly connected components, bipartite checks, union-find and its optimizations, and articulation points and bridges.
- What are connected components, and how do you find them? Pro
- When is union-find a better fit than DFS for components? Pro
- What are strongly connected components in a directed graph? Pro
- How do you check whether a graph is bipartite? Pro
- How do path compression and union by rank speed up union-find? Pro
- How do you maintain connectivity as edges are added over time? Pro
- How do you find articulation points and bridges in a graph? Pro
Shortest paths
BFS for unweighted and multi-source distances, Dijkstra, Bellman-Ford, negative edges and cycles, and how to choose between them.
- How do you find the shortest path in an unweighted graph?
- Why does BFS stop working once edges carry weights? Pro
- How do you choose between BFS, Dijkstra, and Bellman-Ford? Pro
- Why does Dijkstra's algorithm break with negative edge weights? Pro
- When do you need Bellman-Ford instead of Dijkstra? Pro
- How does multi-source BFS work, and when do you use it? Pro
- How does Dijkstra's algorithm find shortest paths? Pro
- How does Bellman-Ford detect a negative-weight cycle in a graph? Pro
Minimum spanning trees
What a minimum spanning tree is, and how Kruskal's and Prim's algorithms build one and when to prefer each.
Edge cases and testing
Disconnected graphs, self-loops, parallel edges, distance overflow, and how to test graph code against tricky inputs.
Advanced shortest paths
DAG relaxation, 0-1 BFS, A-star, bidirectional search, Floyd-Warshall, heap choice, k shortest paths and changing edge weights.
- How do you find shortest paths on a weighted DAG efficiently? Pro
- Does it matter whether Dijkstra uses a binary heap or a Fibonacci heap? Pro
- How does A-star search speed up shortest path, and when does it fail? Pro
- When does bidirectional search help, and what does it require? Pro
- When is Floyd-Warshall the right all-pairs shortest-path choice? Pro
- How does 0-1 BFS beat Dijkstra on 0-or-1 weighted graphs? Pro
- How do you enumerate the k shortest paths between two nodes? Pro
- How do you find shortest paths when edge weights keep changing? Pro
Graphs at scale
Graphs too large for memory, billion-edge limits, huge implicit state spaces, parallel BFS and traversal while the graph is being updated.
- How do you traverse a graph too large for memory? Pro
- How would you parallelize BFS, and what makes it hard? Pro
- How do you make graph traversal safe under concurrent updates? Pro
- How do you track visited state on a huge implicit graph? Pro
- What breaks in your graph code at a billion vertices and edges? Pro
All questions
Showing of 60What is a graph, and what real-world problems does it model?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
A graph is a set of objects plus the relationships between them. The objects become nodes, and each relationship becomes an edge joining two of them. Whenever a problem is about connections, a graph is the natural fit.
Real-world examples include:
- Road maps, where intersections connect by streets
- Social networks, where people connect by friendship
- The web, where pages connect by hyperlinks
- Task schedules, where jobs connect by "must run before"
The payoff is that the same algorithms work on all of these. Questions like "can this node reach that one" or "what is the cheapest route" become the same search over any of them. That reuse is why graphs show up in routing, package managers and recommendation systems.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What are vertices, edges, degree, and neighbors in a graph?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
Vertices are the objects in a graph, and edges are the connections joining pairs of them. People also call vertices nodes, and edges links. A single edge always ties exactly two vertices together.
The neighbors of a vertex are the vertices directly joined to it by an edge. Its degree is how many edges touch it, which equals its neighbor count in a simple graph. In a directed graph, degree splits into in-degree and out-degree.
Degree tells you how connected something is. A social account with degree ten million is a hub you must handle carefully. Neighbors are what every traversal reads next, so storing them cheaply drives your whole performance. Calling a graph sparse means its average degree stays small, and most vertices have few neighbors.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
How do directed and undirected graphs differ, and when do you use each?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
Edges either point one way or go both ways, and that choice is the whole distinction. In an undirected graph an edge means a mutual relationship, like two friends. In a directed graph an edge goes from one vertex to another, like a one-way street or a follow.
The practical effect shows up in reachability. Undirected edges let you travel from either end to the other. Directed edges only let you move along the arrow, so a path from A to B never guarantees a path back.
Pick based on whether the relationship is symmetric.
- Undirected for friendship, two-way roads and network cables
- Directed for follows, web links, and dependencies like task ordering
Getting this wrong breaks logic without an error. If you model "depends on" as undirected, a topological sort becomes meaningless, and cycle checks stop making sense. Match the edge type to the real relationship first.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What does it mean for a graph to be weighted, and why does it matter?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
A weighted graph attaches a number to every edge, standing for cost, distance or time. Some graphs use it for capacity instead. An unweighted graph treats all edges as equal, so every edge counts as one step. Weights change the question from "how few edges" to "how little total cost".
That matters because the cheapest route is often not the shortest by edge count. Three short highway segments can beat one long back road. Weights are miles or minutes on a map, and latency or price on a network.
Breadth-first search finds fewest-edge paths, but it ignores weights and gives wrong answers once they exist. You then need a weight-aware method like Dijkstra. So first ask whether edges carry a real cost, because that decides which algorithm is correct.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
How do an adjacency list and an adjacency matrix store a graph?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
An adjacency list keeps, for each vertex, a list of its neighbors. An adjacency matrix keeps a grid with one row and one column per vertex. The cell at row i, column j marks whether an edge joins those two vertices.
list: A -> [B, C]
matrix: A row = [0, 1, 1, 0]
These two layouts dominate, and they trade memory for lookup speed. A list uses space proportional to O(V + E), which is tiny when edges are few. A matrix always uses O(V^2), even for a nearly empty graph.
Lookup speed favors the matrix. Checking whether a specific edge exists is O(1) in a matrix but needs a scan of the list.
Most real graphs are sparse, so adjacency lists are the default choice. Use the matrix only when the graph is small or dense, or when you test single edges constantly.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
How does breadth-first search explore a graph, step by step?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
Breadth-first search fans out in layers, visiting everything one step away before anything two steps away. You keep a queue of vertices to process and a visited set so you never revisit. Start by marking the source visited and putting it in the queue.
Then repeat until the queue empties:
- Remove the front vertex
- Look at each of its neighbors
- For any unvisited neighbor, mark it visited and add it to the back
Because the queue is first-in first-out, closer vertices always come out first. That is what produces the ring-by-ring order. Each vertex enters the queue once and each edge is examined once, so the cost is O(V + E).
This layered order is exactly why BFS finds the fewest-edge path in an unweighted graph. The first time you reach a vertex, you reached it by the shortest number of hops.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
How does depth-first search explore a graph, step by step?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
Depth-first search follows one path as far as it can before backing up. You pick a start, mark it visited, then move to an unvisited neighbor and repeat. When a vertex has no unvisited neighbors left, you backtrack to the previous one and try its other branches.
You can drive this with recursion, which uses the call stack, or with an explicit stack.
function dfs(v, seen) {
seen.add(v);
for (const n of neighbors(v))
if (!seen.has(n)) dfs(n, seen); // recurse deeper
}
The visited set stops you from looping forever on cycles. DFS visits each vertex once and scans each edge once, so it runs in O(V + E) time, the same as BFS.
That depth-first order makes DFS natural for whole-graph questions, such as detecting cycles, finding connected components and producing a topological order. It suits problems about the graph's overall structure rather than the nearest distance.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
When should you use BFS versus DFS on a graph?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
Use BFS when nearness matters and DFS when the graph's structure matters. Both visit every reachable vertex in O(V + E) time, so the choice is about order and memory, not raw speed. BFS explores by distance, and DFS explores by depth.
BFS finds the fewest-edge path, works well for "closest match" and level-by-level problems, and suits shallow, wide searches. DFS fits cycle detection, connected components and topological sort, where you want to fully explore each branch.
Memory is the other tiebreaker:
- BFS holds a whole frontier, which can be huge on wide graphs
- DFS holds only the current path, but recursion can overflow on very deep graphs
So if you care about shortest hops, or the answer is likely nearby, use BFS. If you care about the graph's overall shape, use DFS.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
How do you find the shortest path in an unweighted graph?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
Plain breadth-first search solves this directly, with no fancier algorithm needed. Because BFS reaches vertices in order of hop count, the first time it touches a vertex is along a fewest-edge path. Every edge counts as one step, so fewest edges means shortest.
To recover the actual route, record where you came from. When you first visit a neighbor, store the vertex you arrived from as its parent. Once you reach the target, walk parent pointers backward to rebuild the path, then reverse it.
parent[neighbor] = current; // set on first visit
The whole thing runs in O(V + E) time and space.
The one catch is that this only holds when every edge has the same cost. Add real weights and fewest edges no longer means cheapest, so BFS gives wrong distances.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What is a path, a cycle, and a connected graph?
What is a topological sort, and when do you need one?
What are connected components, and how do you find them?
What do BFS and DFS cost in time and space, and why?
What is a minimum spanning tree, and where is it used?
How do you detect a cycle in a graph?
When is an adjacency matrix worth its memory cost over a list?
Which representation makes checking if an edge exists fast, and why?
Why can recursive DFS crash where an iterative DFS does not?
Why does BFS stop working once edges carry weights?
How do you choose between BFS, Dijkstra, and Bellman-Ford?
Why does Dijkstra's algorithm break with negative edge weights?
When do you need Bellman-Ford instead of Dijkstra?
How do Kahn's algorithm and DFS-based topological sort differ?
How does topological sort reveal whether a graph has a cycle?
Why must you track visited nodes, and what breaks without it?
When is union-find a better fit than DFS for components?
What are strongly connected components in a directed graph?
How do you check whether a graph is bipartite?
How do you model a grid or maze as a graph?
How do you find shortest paths on a weighted DAG efficiently?
How does multi-source BFS work, and when do you use it?
How do you model task dependencies as a graph to schedule them?
How would you model a social network as a graph?
How do you handle disconnected graphs during a traversal?
How do self-loops and parallel edges affect your algorithms?
How does Dijkstra's algorithm find shortest paths?
How does Bellman-Ford detect a negative-weight cycle in a graph?
How do path compression and union by rank speed up union-find?
How does Kruskal's algorithm use union-find to build an MST?
How does Prim's algorithm differ from Kruskal's, and when do you prefer each?
How do you traverse a graph too large for memory?
What is compressed sparse row, and why does it beat adjacency lists?
How does pointer chasing in adjacency lists hurt cache performance?
How would you parallelize BFS, and what makes it hard?
How do you make graph traversal safe under concurrent updates?
Does it matter whether Dijkstra uses a binary heap or a Fibonacci heap?
How does A-star search speed up shortest path, and when does it fail?
When does bidirectional search help, and what does it require?
When is Floyd-Warshall the right all-pairs shortest-path choice?
How do you track visited state on a huge implicit graph?
How does 0-1 BFS beat Dijkstra on 0-or-1 weighted graphs?
How do you guard against distance overflow in shortest-path code?
How do you maintain connectivity as edges are added over time?
What breaks in your graph code at a billion vertices and edges?
How do you find articulation points and bridges in a graph?
How do you enumerate the k shortest paths between two nodes?
How do you find shortest paths when edge weights keep changing?
How would you stream a topological order without loading everything?
How do you choose between a visited array and a hash set?
How do you test and debug a graph algorithm on tricky inputs?
This answer is part of Pro.
The full written answer, with the trade-offs and follow-ups an interviewer will probe.
No matches
Try a different filter or search term.
Graphs in pictures.
A quick recap of Graphs in 27 short animated pictures, one idea at a time. About 7 min to get the whole topic back in your head before you walk in. Pause any picture, slow it down, or step through it.
Pro The first chapter is free to play. The other 25 pictures come with Pro.
This picture is part of Pro. The first chapter is free to play; the other 25 pictures come with Pro.
Get Pro · $10/mo Already Pro? Sign in51 of 60 Graphs answers are in Pro.
Full answers, code samples, and AI explanations that go simpler or deeper. Cancel anytime.
- Full answers + code
- AI explanations, simpler or deeper
- 1,000 AI credits / month
- Cancel anytime
Change topic
Pick a different technology or stack. Your current topic stays put until you choose a new one.
MEAN
MongoDB, Express, Angular, Node.jsMERN
MongoDB, Express, React, Node.jsDjango
Python Full-Stack DevelopmentRuby on Rails
Convention over ConfigurationServerless on AWS
Serverless Architecture on AWSInterviewers also test these - they're common to every stack, whichever one you picked above.
Flutter Mobile
Flutter Cross-Platform Mobile DevelopmentInterviewers also test these - they're common to every stack, whichever one you picked above.
Spring Boot
Enterprise Java Development.NET
Microsoft EcosystemVue
Vue.js, Vite, TypeScript, Tailwind, Node.jsGo Backend
Golang, gRPC, PostgreSQL, Redis, RabbitMQInterviewers also test these - they're common to every stack, whichever one you picked above.
FastAPI
Python, FastAPI, SQLAlchemy, PostgreSQLReact Native
React, TypeScript, Redux, FirebaseiOS Native
Swift, SwiftUI, UIKit, FirebaseAndroid Native
Java, Jetpack Compose, FirebaseDevOps / Platform
Docker, Kubernetes, Terraform, CI/CDInterviewers also test these - they're common to every stack, whichever one you picked above.
AI Engineer
LLMs, RAG, Agents, EvalsAI-Powered Developer
Claude Code, Copilot, Agentic WorkflowsCore SWE Interview Prep
Data structures, algorithms, OS, concurrency, networking, gitInterviewers also test these - they're common to every stack, whichever one you picked above.
Interviewers also test these - they're common to every stack, whichever one you picked above.