Graph Theory37 sections · 1633 units
Open in Course

The Two-BFS Trick

Start anywhere, go far twice

Here is the core idea: start BFS from any random node. Find the farthest node from it. Call that node uu. Now run BFS from uu and find the farthest node from uu. Call that vv. The distance from uu to vv is the diameter.

Two BFS runs instead of nn runs. That is O(n)O(n) total time.

This works because one endpoint of the longest path will always be the farthest node from your starting point. I'll prove why in the next unit.

Space complexity is O(n)O(n) for the data structures used.