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?

  1. A. DFS also guarantees shortest paths, just slower
  2. B. BFS uses less memory than DFS in every case
  3. 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
  4. 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

Exams that ask this topic