Free, open courseware in graph theory and optimization

learngraphtheory.org Algorithms · Optimization · Open courseware
Interview prep book

Graph Algorithms for Coding Interviews

100 Solved Problems with Visual Explanations and Python Solutions

By Mohammed Islam Hadjoudj, creator of Learn Graph Theory

  • 100 solved problems
  • Visual explanations
  • Python solutions
  • Kindle & paperback
See it on Amazon →

Kindle and paperback. Prices are shown on Amazon.

About the Book

Graph Algorithms for Coding Interviews prepares you for the graph questions in technical interviews with 100 solved problems. Every problem comes with a visual explanation that shows the algorithm step by step and a complete Python solution.

Graph questions are where many candidates freeze: the problem talks about courses, islands, flights or friends, and the graph is hidden in the story. The way through is practice with feedback. You need to see enough problems to recognise the pattern, and you need to see each algorithm move before you can trust your own code under pressure. This book gives you both.

Who It Is For

What a Problem Looks Like

Here is a classic interview problem worked in the style of the book, written for this page: the problem, the picture that cracks it, and the Python solution.

Example · Topological sort · Cycle detection

Can you finish all the courses?

There are n courses, numbered 0 to n − 1. Each pair [a, b] in prerequisites means you must take course b before course a. Return True if you can finish every course.

Spot the graph. Courses are vertices and each prerequisite is a directed edge b → a. You can finish everything exactly when this directed graph has no cycle, so the question is really: does a topological order exist?

0 1 2 3 in-degree 0 in-degree 1 in-degree 1 in-degree 2
prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]. Only course 0 has no prerequisite, so it goes first.

The idea (Kahn's algorithm). Repeatedly take a course whose prerequisites are all done (in-degree 0), and remove its outgoing edges. If you manage to take all n courses, there is no cycle. If you get stuck early, the courses left over sit on a cycle.

TakeIn-degrees after (0, 1, 2, 3)Queue
–0, 1, 1, 2[0]
0–, 0, 0, 2[1, 2]
1–, –, 0, 1[2]
2–, –, –, 0[3]
3–, –, –, –[]

All four courses are taken, so the answer is True. Add the pair [1, 3] and courses 1 and 3 wait for each other: after taking 0 and 2 the queue is empty, only 2 of 4 courses are done, and the answer is False.

from collections import deque

def can_finish(n, prerequisites):
    graph = [[] for _ in range(n)]
    indegree = [0] * n
    for course, before in prerequisites:
        graph[before].append(course)
        indegree[course] += 1

    queue = deque(v for v in range(n) if indegree[v] == 0)
    taken = 0
    while queue:
        v = queue.popleft()
        taken += 1
        for w in graph[v]:
            indegree[w] -= 1
            if indegree[w] == 0:
                queue.append(w)
    return taken == n


print(can_finish(4, [[1, 0], [2, 0], [3, 1], [3, 2]]))          # True
print(can_finish(4, [[1, 0], [2, 0], [3, 1], [3, 2], [1, 3]]))  # False

Complexity. Every course enters the queue at most once and every edge is looked at once, so the time is O(V + E) and the extra space is O(V + E) for the adjacency list. See it run in the topological sort visualizer.

Free Practice on This Site

Use these free pages next to the book: question lists to test yourself, and visualizers to watch an algorithm run on your own graph.

For a one-page review the night before, keep the graph algorithms cheat sheet and the complexity table open, and read which graph algorithms come up in interviews.

Which of the Two Books Is for You?

Mohammed Islam Hadjoudj has written two graph books with different jobs. Pick by what you need to do next.

Graph Theory Through ProblemsGraph Algorithms for Coding Interviews
GoalUnderstand the theory and pass a graph theory course or examSolve graph questions in technical interviews
Contents300 exercises over 13 chapters100 solved interview problems
SupportHints for the harder exercises and a complete solution to every oneA visual explanation and a Python solution for every problem
StyleProofs, and algorithms run by hand in step tablesCode you can run and adapt
FormatsKindle and paperbackKindle and paperback

About the Author

Mohammed Islam Hadjoudj

Mohammed Islam Hadjoudj holds a Master's degree in Operations Research and a Bachelor's degree in Mathematics, built Learn Graph Theory (the free interactive visualizer, lessons and article library on this site) and works on combinatorial optimization and scheduling problems.

· Try the visualizer

Frequently Asked Questions

What language are the solutions in?

Python. Every one of the 100 problems has a complete Python solution.

How many problems are in Graph Algorithms for Coding Interviews?

100 solved problems, each with a visual explanation that shows the algorithm step by step and a complete Python solution.

Is it available on Kindle?

Yes. The book is available as a Kindle ebook and as a paperback on Amazon.

How is it different from practising on LeetCode?

Coding sites give you problems and a judge. This book explains each problem: it shows the algorithm moving step by step in pictures and walks through a complete solution, so you learn the pattern and not only the accepted answer. The two work well together.

Who wrote Graph Algorithms for Coding Interviews?

Mohammed Islam Hadjoudj, who holds a Master's degree in Operations Research and a Bachelor's degree in Mathematics and created the Learn Graph Theory website and its interactive algorithm visualizer.

Disclosure: this page is written by the author of the book, who also runs this site. Example problems on this page were written for this page to show the style of the book.

Walk Into the Graph Round Prepared

100 solved problems, a picture of every algorithm, and Python you can run.

See it on Amazon →