Back to blog

Graph Algorithms for Interviews

27 February 20262 min read

Representing a Graph

  • Adjacency list: List of neighbors per node. Best for sparse graphs and traversal.
  • Adjacency matrix: matrix[i][j] = weight or 1/0. Best for dense graphs or O(1) edge lookup.

Use a queue. Explores level by level.

When to use: Shortest path in unweighted graphs, level-order, connected components.

Interview favorites: Number of islands, word ladder, clone graph.

Use recursion or a stack. Explores as deep as possible first.

When to use: Cycle detection, topological sort, path finding, connected components.

Interview favorites: Clone graph, number of islands, course schedule.

Topological Sort

Ordering of nodes in a DAG. Kahn's algorithm (BFS): in-degrees and queue. DFS: push after visiting descendants, then reverse.

When to use: Course schedule, task scheduling, dependency order.

Dijkstra's Algorithm

Shortest path from one source with non-negative edge weights. Use a min-heap keyed by distance.

When to use: Weighted shortest path, network delay time.

Quick Reference

GoalAlgorithmNotes
Shortest path (unweighted)BFSLevel = distance
Shortest path (non-negative)DijkstraMin-heap
Cycle detectionDFSGray/black
Dependency orderTopo sortKahn or DFS

Master these and you'll be ready for most graph interview questions. Practice with Preplume(/) timelines.

Related posts

Common DSA Mistakes and How to Avoid Them

Typical mistakes in coding interviews: off-by-one errors, wrong complexity, and how to avoid them.

14 Mar 20262 min readRead more