Data Structures & AlgorithmsHardProduct Company SDE · CP practice
Problem: Which of these correctly explains why BFS (not DFS) is used to find the shortest path in an unweighted graph?
- A. DFS also guarantees shortest paths, just slower
- B. BFS uses less memory than DFS in every case
- C. BFS explores nodes in strictly increasing order of distance from the source, so the first time a node is reached is guaranteed to be via a shortest path
- D. Shortest paths require Dijkstra's algorithm even for unweighted graphs
Correct answer: C. BFS explores nodes in strictly increasing order of distance from the source, so the first time a node is reached is guaranteed to be via a shortest path
Because BFS processes all nodes at distance d before any at distance d+1, the first visit to any node necessarily happens along one of its shortest (fewest-edges) paths from the source; DFS can reach a node via a much longer path first.
More Coding Interview Problems questions
- Problem: What is the time complexity of detecting a cycle in an undirected graph using Union-Find, processing E edges?
- Problem: A recursive solution explores every possible way to partition a string into palindromic substrings (palindrome partitioning)…
- Problem: Which best describes the relationship between the number of valid Binary Search Trees on n distinct keys and the Catalan numbers?
- Problem: What is the time complexity of the standard iterative binary search, and what precondition must hold for it to work correctly?
- Problem: Which best describes why DFS-based topological sort (using finish times, pushing to a stack) correctly produces a topological…
- Problem: A problem requires finding all pairs in an array that sum to a target, allowing duplicate pairs to be counted once. Which is the…