Skip to the page

Graphs and grids · mid

Graph basics

Store a graph as an adjacency list. Use BFS for shortest paths when edges have no weights, DFS for reachability and cycles, and Kahn's algorithm (in-degrees plus a queue) for dependency order.

The notes

What you must know

  • Adjacency list: a list of neighbour lists (Java List<List<Integer>>, Python list of lists or defaultdict(list), C++ vector<vector<int>>); for undirected edges add both directions.
  • BFS shortest path (unweighted): queue + visited; mark a node visited when you ENQUEUE it, not when you dequeue it, or nodes are added many times.
  • Topological sort (Kahn): count in-degrees; queue the nodes with 0; pop, append to the order, decrement the neighbours; if the order has fewer than n nodes there is a cycle.
  • Cycle in a directed graph by DFS needs three states (not visited, in progress, done); meeting an 'in progress' node means a back edge.
  • Typical uses: package and build order, course prerequisites, dependency graphs, org charts (Employee Importance), maps.
  • Complexity O(V + E) for BFS, DFS and Kahn. Weighted shortest paths need Dijkstra with a min-heap: O((V + E) log V).

The red pen

Common traps: mistake → fix

  • Mistake: Use one visited flag for directed cycle detection

    Fix: it reports false cycles for diamond shapes; use three states or Kahn.

  • Mistake: BFS gives shortest paths with weights

    Fix: only for equal weights; weighted edges need Dijkstra.

  • Mistake: A topological order is unique

    Fix: many orders can be valid; state a tie-break rule if tests need one.

Easy to hard

Questions interviewers ask, easy to hard

  1. Shortest number of steps between two nodes.
  2. Can all courses be finished given prerequisites?
  3. Return a valid build order for packages; what if there is a cycle?
  4. Which items need a new value after one item changes, and in what order?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview