Graph Traversal, Cycle Detection and Topological Sort | DSA Interview Patterns - Study Chapter | QuizMaker

Pick DFS, BFS, Kahn's algorithm, or Euler-style DFS based on reachability, cycles, and ordering constraints.

Read
20m
Type
Chapter
Access
Free

Course

DSA Interview Patterns Roadmap

Topic

Graphs BFS and DFS

Learning Outcome

Pick DFS, BFS, Kahn's algorithm, or Euler-style DFS based on reachability, cycles, and ordering constraints.

Pattern Recognition

ItemDetail
Core signalThe problem contains dependencies, prerequisites, directed edges, components, or must-use-all-edges requirements.
Use whenGraph structure is explicit or can be built from relationships in the input.
Avoid whenThe required invariant is not monotonic or the input constraints point to a simpler direct scan.

Intuition

Traversal answers reachability; topological sort answers dependency order; DFS path state detects directed cycles.

Exact Practice Question Names

Interview Approach

  1. Build adjacency lists carefully.
  2. Use parent check for undirected cycles.
  3. Use pathVis or indegree for directed cycles.
  4. Use min-heap/multiset when lexical order matters.
  5. For SCC, use Kosaraju or Tarjan after basic DFS is solid.

Pseudocode

build graph and indegree
queue = nodes with indegree 0
while queue not empty:
  node = pop
  order.add(node)
  for nei in graph[node]:
    indegree[nei] -= 1
    if indegree[nei] == 0: push nei
if order size != n: cycle exists

Sample Dry Run

For Course Schedule, courses with no prerequisites enter the queue first. If a cycle remains, some indegrees never become zero.

Edge Cases

Common Mistakes

Complexity

ItemDetail
Expected timeO(V + E), plus sorting cost if adjacency order matters.
Expected spaceO(V + E).

Java, C++ and Python Notes

Quick Revision Checklist

Tags

Open on QuizMaker