FresherFresher (0–1 yrs)PythonAmazonMicrosoftAdobe
BFS vs DFS interview
When do you choose BFS vs DFS for graph/tree problems? Give complexity and one example each.
Answers use simple, clear English.
Quick interview answer
BFS (queue): shortest path in unweighted graphs, level-order. DFS (stack/recursion): path existence, topological sort variants, connected components, tree recursion. Both O(V+E).
Detailed answer
BFS (queue): shortest path in unweighted graphs, level-order. DFS (stack/recursion): path existence, topological sort variants, connected components, tree recursion. Both O(V+E). DFS uses O(h) stack; BFS O(width). Prefer iterative DFS/BFS if recursion depth risk.
Real example & use case
BFS: maze fewest steps. DFS: detect cycle in directed graph via colors.
Pros & cons
Pros: right tool clarity. Cons: wrong choice wastes time in interviews.
#dsa#bfs#dfs