Graph Coding Problems: 50 Questions with Solutions
50 graph coding problems — 5 easy · 36 medium · 9 hard — with solutions in 13 languages. Plus a step-by-step walkthrough and a 8-day plan.
- Problems: 50
- By difficulty: 5 easy · 36 medium · 9 hard
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
- Cost: Free on every plan; sign in to run and submit
Nodes and edges: build the adjacency list, then traverse it. These problems cover the representation choices (list, matrix, edge list), reachability and components, cycle detection in directed and undirected graphs, and the traversals that everything else is built on. Shortest paths and topological order have their own pages.
How graph works, step by step
n = 5, edges = [[0,1], [0,2], [1,2], [1,3], [2,4], [3,4]]- An edge list names the joined pairs, but finding one node's neighbours would mean scanning all 6 edges. An adjacency list gives each of the 5 nodes its own list instead, filled in a single pass over the edges.
- Read edge 0–1: append 1 to adj[0], now [1], and 0 to adj[1], now [0]. The graph is undirected, so every edge is written twice, once from each end.
- Read edge 0–2: append 2 to adj[0], now [1, 2], and 0 to adj[2], now [0]. 2 had no neighbours until now; appending to the end of a list is O(1), however long it is.
- Read edge 1–2: append 2 to adj[1], now [0, 2], and 1 to adj[2], now [0, 1]. 1 and 2 were already linked through 1–0–2, so this edge closes a cycle; the lists still only record direct neighbours.
- Read edge 1–3: append 3 to adj[1], now [0, 2, 3], and 1 to adj[3], now [1]. A list's length is its node's degree: 1 now has 3 neighbours, while 3 gets its first.
- Read edge 2–4: append 4 to adj[2], now [0, 1, 4], and 2 to adj[4], now [2]. Only the two lists the edge names are touched, which is why the whole pass costs O(V + E).
- Read edge 3–4: append 4 to adj[3], now [1, 4], and 3 to adj[4], now [2, 3]. This closes a second cycle, 3–1–2–4–3, and is stored exactly like any other edge.
- All 6 edges are in, each stored twice, so the lists hold 12 entries: the degrees add up to 2E. Building took O(V + E), and now 1's neighbours are one lookup, adj[1] = [0, 2, 3], in O(degree) instead of an O(E) scan.
Graph study plan
14 of the 50 Graph problems (4 easy, 7 medium and 3 hard) over 8 days, about 8 h 10 min in all — the pattern first, then easiest to hardest. After that, the other 36 in the full list below are practice at your own pace. Then move on to Breadth-First Search.
Day 1
Learn the pattern: read the essentials and step through the walkthrough above, then solve these 3.
Day 2
Medium problems: the same pattern with one twist each. Name the twist before you code.
- Find Champion I Easy
- Keys and Rooms Medium
Day 3
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Number of Provinces Medium
- Course Schedule Medium
Day 4
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Course Schedule II Medium
- Redundant Connection Medium
Day 5
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
Day 6
Hard problems: the pattern combined with a second idea. Give each a full attempt before reading the editorial.
Day 7
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
Day 8
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
Graph: the essentials
When to reach for it
Anything with pairwise relationships — roads between cities, prerequisites, friendships, trust, network links — even when the word "graph" never appears. Inputs usually arrive as an edge list ([[u, v], …]) or an adjacency matrix. Before writing anything, settle three things: are edges directed, do they carry weights, and are nodes numbered from 0 or from 1?
The pattern
Convert to an adjacency list, then choose the traversal: Breadth-First Search for the fewest edges, depth-first search for reachability and structure, union-find when edges arrive one at a time and only connectivity matters. Some questions need no traversal at all: in Find the Town Judge, the judge is the node with in-degree n − 1 and out-degree 0.
def build(n, edges, directed=False):
adj = [[] for _ in range(n)] # nodes 0..n-1
for u, v in edges:
adj[u].append(v)
if not directed:
adj[v].append(u)
return adj
Cost
An adjacency list takes O(V + E) space and a full traversal O(V + E) time. An adjacency matrix takes O(V²) space and makes every traversal O(V²); it pays off only for dense graphs or constant-time edge checks.
Common mistakes
- Adding an undirected edge in one direction only.
- Missing isolated nodes: loop over
range(n), not over the nodes that appear in edges, when counting components. - Undirected cycle detection that treats the edge back to the parent as a cycle.
- Traversing from node 0 and assuming that reaches the whole graph.
Start with
- Find the Town Judge: degrees instead of a traversal.
- Find if Path Exists in Graph: build the list, then search.
- Is Graph Bipartite?: two-colouring every component.
All graph problems
Easy (5)
- Find Champion II
- Find Champion I Array, Matrix
- Find if Path Exists in Graph Union Find, Breadth-First Search
- Find the Town Judge Hash Table
- Find Center of Star Graph
Medium (36)
- Number of Ways to Arrive at Destination Dynamic Programming, Shortest Path, Topological Sort
- Course Schedule IV Topological Sort, Depth-First Search, Breadth-First Search
- Parallel Courses Topological Sort, Breadth-First Search
- Detonate the Maximum Bombs Array, Math, Depth-First Search
- The Maze II Array, Matrix, Breadth-First Search
- Loud and Rich Array, Topological Sort, Depth-First Search
- Shortest Path with Alternating Colors Breadth-First Search
- Number of Nodes in the Sub-Tree With the Same Label Hash Table, Tree, Depth-First Search
- Minimum Fuel Cost to Report to the Capital Tree, Depth-First Search, Breadth-First Search
- Maximum Star Sum of a Graph Array, Greedy, Sorting
- Count the Number of Complete Components Union Find, Depth-First Search, Breadth-First Search
- Minimum Score of a Path Between Two Cities Union Find, Depth-First Search, Breadth-First Search
- Reachable Nodes With Restrictions Array, Tree, Depth-First Search
- Minimum Swaps to Sort Array, Sorting
- Count Unreachable Pairs of Nodes in an Undirected Graph Depth-First Search, Breadth-First Search, Union Find
- Maximum Total Importance of Roads Greedy, Sorting, Heap
- Find Closest Node to Given Two Nodes Depth-First Search
- Maximal Network Rank
- Reorder Routes to Make All Paths Lead to the City Zero Depth-First Search, Breadth-First Search
- Possible Bipartition Depth-First Search, Breadth-First Search, Union Find
- Minimum Height Trees Depth-First Search, Breadth-First Search, Topological Sort
- Number of Operations to Make Network Connected Depth-First Search, Breadth-First Search, Union Find
- Minimum Number of Vertices to Reach All Nodes
- Find Eventual Safe States Depth-First Search, Breadth-First Search, Topological Sort
- All Paths From Source to Target Backtracking, Depth-First Search, Breadth-First Search
- Keys and Rooms Depth-First Search, Breadth-First Search
- Is Graph Bipartite? Depth-First Search, Breadth-First Search, Union Find
- Graph Valid Tree Depth-First Search, Breadth-First Search, Union Find
- Number of Connected Components in an Undirected Graph Depth-First Search, Breadth-First Search, Union Find
- Min Cost to Connect All Points Minimum Spanning Tree, Union Find
- Cheapest Flights Within K Stops Dynamic Programming, Shortest Path
- Network Delay Time Shortest Path, Heap
- Redundant Connection Union Find
- Course Schedule II Topological Sort, Heap
- Course Schedule Topological Sort, Depth-First Search
- Number of Provinces Depth-First Search, Union Find
Hard (9)
- Minimum Time to Visit a Cell In a Grid Array, Matrix, Breadth-First Search
- Checking Existence of Edge Length Limited Paths Array, Union Find, Sorting
- Find All People With Secret Union Find, Depth-First Search, Breadth-First Search
- Minimum Obstacle Removal to Reach Corner Array, Matrix, Breadth-First Search
- Number of Good Paths Array, Tree, Union Find
- Critical Connections in a Network Depth-First Search, Biconnected Component
- Number of Restricted Paths From First to Last Node Dynamic Programming, Shortest Path, Heap (Priority Queue)
- Shortest Path Visiting All Nodes Bit Manipulation, Breadth-First Search, Bitmask
- Longest Cycle in a Graph Depth-First Search, Topological Sort
Companies that ask graph problems
- Amazon 40 problems on graph
- Google 39 problems on graph
- Microsoft 12 problems on graph
- Meta 8 problems on graph
- Adobe 3 problems on graph
- Salesforce 2 problems on graph
- Uber 2 problems on graph
- Accenture 1 problem on graph
- Bloomberg 1 problem on graph
- Flipkart 1 problem on graph
- Infosys 1 problem on graph
- LinkedIn 1 problem on graph
Next topic: Breadth-First Search