What is the difference between DFS and BFS in terms of space complexity?
Answer
Both BFS and DFS are O(V) space in the worst case, but their space usage patterns differ significantly: DFS space complexity: O(h) where h = maximum depth of the recursion/stack. For a balanced binary tree: O(log n). For a skewed tree (linked list-like): O(n). For a general graph with V vertices: O(V) worst case. DFS only needs to remember the current path from root to current node — efficient for deep, narrow trees. Uses a stack (call stack for recursive, explicit stack for iterative). BFS space complexity: O(w) where w = maximum width of the graph at any level. For a balanced binary tree: O(n/2) = O(n) — the last level has n/2 nodes, all in the queue at once. For a path graph (linked list): O(1) — only 1 node at each level. BFS needs to store all nodes at the current level — memory-intensive for wide trees. Uses a queue. Practical implications: BFS is memory-intensive for wide, shallow graphs; DFS is stack-intensive for deep, narrow graphs. For very wide graphs (e.g., shortest 6-degrees-of-separation in a social network where each person has 500 friends), BFS memory usage grows as 500^level — impractical. Bidirectional BFS addresses this by searching from both ends, reducing queue size from 500^6 to 2×500^3. Iterative deepening DFS (IDDFS) combines BFS's level-by-level exploration with DFS's O(depth) space.