Question presented to candidate: "Explain the difference between breadth-first search and depth-first search on a graph. Then implement both in Python and tell me when you would choose one over the other."
What a strong answer should cover:
- The one structural difference: BFS uses a FIFO queue, DFS uses a LIFO stack (or recursion).
- Visit order: BFS goes level by level, DFS goes deep then backtracks; both need a visited set for cycles.
- Both are O(V + E) time; memory is the widest level for BFS and the deepest path for DFS.
- BFS gives shortest paths in unweighted graphs; DFS does not. Typical uses of each (topological sort, cycle detection, backtracking vs nearest/minimum steps).
- Python details:
collections.dequewithpopleft()(notlist.pop(0)), and the default recursion limit of 1000 that breaks recursive DFS on deep graphs.
Code / implementation expected: Yes โ BFS with deque and DFS both recursively and with a list used as a stack, in Python.