Verified Jobs Live
Data Structures & Algorithms Medium Level ~3 min read

When does breadth-first search find a shortest path, and when is it the wrong choice?

Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Model Answer & Deep-Dive Explanation

Breadth-first search explores vertices by edge distance and finds shortest paths in an unweighted graph, or when every edge has the same cost. Mark vertices when enqueuing to avoid repeated work and retain parents to reconstruct a path. With adjacency lists, runtime is O(V + E). Unequal edge weights invalidate the ordinary BFS guarantee: use Dijkstra’s algorithm for nonnegative weights or an appropriate algorithm when negative weights exist. Clarify whether the graph is directed and whether unreachable destinations should retu an empty result or an explicit failure.