What is Depth-First Search (DFS)?

Why Interviewers Ask This

This is a classic screening question for Data Structures & Algorithms roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

DFS explores a graph by going as deep as possible along a branch before backtracking. Uses a stack (or recursion). Algorithm (recursive): mark current node visited, process it, for each unvisited neighbor, recursively DFS. Iterative: use an explicit stack — push source, while stack not empty: pop, if unvisited mark visited and push all unvisited neighbors. Time: O(V+E). Space: O(V) for visited set and stack. Properties: explores one complete path before backtracking; order depends on neighbor order; not guaranteed shortest path. Applications: (1) Cycle detection in directed/undirected graphs; (2) Topological sort; (3) Connected components and SCCs (Tarjan's, Kosaraju's); (4) Maze solving; (5) Pathfinding (doesn't guarantee shortest); (6) Tree traversals (in/pre/post-order are all DFS); (7) Backtracking problems (N-Queens, Sudoku); (8) Finding bridges and articulation points; (9) Detecting all paths. DFS memory advantage: only needs O(h) space (recursion depth) vs BFS's O(w) (width). Choose DFS for exhaustive search, cycle detection, and connectivity.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.