Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Graphs

Meet in the Middle.

Watch the explainer

A single breadth-first search grows one expanding ball of explored nodes until it swallows the goal — and that ball’s size explodes with distance. Bidirectional BFS runs two searches at once: one forward from the start, one backward from the goal, each stopping when its frontier touches the other’s. Two small balls that meet in the middle explore dramatically fewer nodes than one big ball — turning roughly b^d into 2·b^(d/2). Step the two frontiers and watch them collide.

explores ~2·b^(d/2) vs b^d nodes · needs a known goal & reversible edges
forward frontier

The BFS wave growing outward from the start.

backward frontier

The BFS wave growing outward from the goal (over reversed edges).

meeting

When a node is reached by both searches — the frontiers have touched.

shortest path

Stitch the forward path to the meeting node with the backward path from it.

bidi.js — two frontiers, one meeting point
Ready
A grid with a start (left) and goal (right). One BFS grows from each. Step expands both frontiers by one layer; they stop the instant they touch.
2
bidi explored
–
1-way BFS
0
layers

How it works

The saving is exponential, and it comes straight from the geometry. A one-way BFS to a goal at distance d explores on the order of b^d nodes (branching factor b). Split the job in half and each search only has to reach distance d/2 before they meet — exploring about b^(d/2) nodes each, or 2·b^(d/2) total. Because the exponent is halved, even a modest distance turns a huge search into a small one.

1

Two frontiers, alternating

Keep a BFS frontier from the start and another from the goal. Each step, expand both by one layer, marking newly-reached cells for each side.

2

Watch for a touch

After expanding, check whether any cell is now reached by both sides. The first such cell is where the two shortest half-paths join.

3

Stitch the path

Follow parent pointers from the meeting cell back to the start (forward search) and forward to the goal (backward search), then join the two halves.

✓

When it applies

You need a known goal (so you can search backward from it) and edges you can traverse in reverse. Given both, bidirectional BFS finds the same shortest path as BFS while exploring far fewer nodes.

One-way BFS
~b^d
Bidirectional
~2·b^(d/2)
Finds
shortest path
Needs
known goal

The code

# expand the smaller frontier each round; stop when they meet def bidirectional_bfs(adj, start, goal): if start == goal: return [start] fwd = {start: None}; bwd = {goal: None} # node -> parent front, back = {start}, {goal} while front and back: if len(front) > len(back): front, back, fwd, bwd = back, front, bwd, fwd nxt = set() for u in front: for v in adj[u]: if v in bwd: return stitch(fwd, bwd, u, v) # frontiers touched if v not in fwd: fwd[v] = u; nxt.add(v) front = nxt
▶  Watch it explained

Bidirectional BFS: Time and Space Complexity, From First Principles

Quick check

1. Why does bidirectional BFS explore far fewer nodes than one-way BFS?

2. What does bidirectional BFS require that plain BFS does not?

3. How is the shortest path recovered when the frontiers meet?

FAQ

What is bidirectional BFS?

A shortest-path search running two breadth-first searches at once — forward from the start, backward from the goal — stopping when their frontiers meet. Each search reaches only half the distance, so it explores ~2·b^(d/2) nodes instead of b^d.

When can you use bidirectional BFS?

When you have a single known goal (to search backward from) and reversible edges, on unweighted graphs where BFS gives shortest paths. It doesn’t apply with an unknown goal, many goals, or non-reversible edges.

How much faster is it than one-way BFS?

Explored nodes drop from ~b^d to ~2·b^(d/2). Halving the exponent is exponential — e.g. b=10, d=6 is ~1,000,000 nodes one-way versus ~2,000 bidirectional.

How does it compare to A* search?

Bidirectional BFS shrinks the search from both ends; A* shrinks it with a heuristic steering toward the goal. They’re complementary (bidirectional A* combines them). BFS-both-ends needs no heuristic but needs a known goal and reversible edges.

The picture: two small balls instead of one big one

One-way BFS: nodes found after k layers102152831742655267671488202936410 Bidirectional BFS: both sides, after r rounds2041102163344525
Node counts from running both searches on a ternary tree of 364 nodes (every node has three children, edges can be walked both ways). The start and goal are the leftmost and rightmost leaves, 10 edges apart. Top row: one-way BFS, nodes found after k layers. Bottom row: bidirectional BFS, both sides added together, after r rounds. One-way ends up discovering the whole tree; the two frontiers touch after discovering 52.

Worked example, step by step

Take the ternary tree above, where node n has children 3n+1, 3n+2, 3n+3 and a parent (n−1)//3. The start is leaf 121, the goal is leaf 363, and the shortest path is 10 edges long, up through the root and back down. Each round expands the whole forward layer, then the whole backward layer, and checks every neighbour against the other side as it is found.

RoundSideDepth reachedNew nodesForward seenBackward seenTouched?
1forward1121no
1backward1122no
2forward2352no
2backward2355no
3forward3385no
3backward3388no
4forward49178no
4backward491717no
5forward592617no
5backward592626yes, at the root

Read the last row first: the backward search finds that the root is already in the forward set, and the path length is 5 + 5 = 10. The whole search discovered 52 nodes. A one-way BFS from the same leaf has to finish layer 10 before it can see the goal, by which point it has discovered all 364 nodes. The growth rate is the lesson. Each side adds 1, 3, 3, 9, 9 nodes per layer: the frontier triples every second layer, so what you pay is set by the deepest layer you reach, and depth 5 is far cheaper than depth 10. Here the tree is tiny and the saving is 364 against 52; with a branching factor of 10 and a distance of 6 the same argument gives roughly a million against two thousand.

Common mistakes

  • Stopping on the first touch while expanding one node at a time

    The page's version finishes whole layers. If you pop one node from each side in turn and return the moment a neighbour is on the other side, the first contact is not always the shortest. On 2,000 random undirected graphs (30 nodes, 45 random edges) the one-node-at-a-time version returned a wrong length 93 times; the layer-synchronised version returned a wrong length 0 times. The first failing case had a true distance of 3 and returned 4.

  • Reusing the forward adjacency for the backward search

    On a directed graph the backward frontier has to follow edges in reverse, which means building a reversed adjacency list first. Reusing adj for both sides gave an answer different from plain BFS on 1032 of 2000 random directed graphs (30 nodes, 60 edges), for example returning 4 where the true distance was 10. The two searches then meet at a node that cannot actually be walked from the start to the goal in the claimed direction.

  • Skipping the start == goal check

    With both sides seeded with the same node, the first expansion never sees a touch immediately. On the two-node graph 0 — 1 with start and goal both 0, the unguarded loop returned a path length of 2 (out to node 1 and back), when the answer is 0.

  • Always expanding the same side

    The point of the algorithm is that each side stays small. If you always expand the forward side, you have written ordinary BFS with extra bookkeeping. Going from the root of the same tree to a leaf at depth 5, expanding the smaller frontier discovered 18 nodes, strict alternation discovered 44, and forward-only discovered all 364.

  • Using it on weighted edges

    Fewer hops is not lower cost. With edges S–G of weight 10, S–A of weight 1 and A–G of weight 1, the frontiers touch after one hop and report the direct edge (cost 10) when the cheapest path S–A–G costs 2. Use Dijkstra, or bidirectional Dijkstra, which has a different stopping rule.

Where this shows up

  • Degrees of separation

    Shortest connection between two people in a social or collaboration graph is the classic case. Both ends are known, friendship edges run both ways, and the branching factor is large enough that the half-depth trick matters enormously.

  • Word ladders and puzzle solvers

    Turning one word into another by changing one letter at a time, or solving a sliding-tile or cube position from a known solved state, are searches with a known goal and reversible moves. Meeting in the middle is the standard speed-up.

  • Route planning

    Road-network routers commonly run a forward search from the origin and a backward search from the destination. With weights the stopping rule changes (you cannot stop at the first touch), but the two-ball geometry is the same.

  • Interview questions

    Word Ladder is the textbook interview problem where the one-way solution passes small tests and times out on large ones, and bidirectional BFS is the expected next step.

Complexity and trade-offs

CaseTimeSpaceWhy
Bidirectional BFS, smaller frontier firstO(b^(d/2))O(b^(d/2))Both visited sets are kept. Root to leaf on the 364-node tree discovered 18 nodes.
Bidirectional BFS, strict alternationO(b^(d/2))O(b^(d/2))Same bound, but a lopsided graph wastes work: 44 nodes on the same root-to-leaf search.
One-way BFSO(b^d)O(b^d)Discovered all 364 nodes on both searches (leaf to leaf, and root to leaf).
Directed graph, extra stepO(V + E) to buildO(E) extraThe backward search needs a reversed adjacency list, built once before searching.

Leaf to leaf, the two frontiers discovered 52 nodes against 364 for one-way BFS, and the one-way search's memory is the larger since it must hold every node it found. The cost is requirements, not code: you must know the goal, be able to walk edges backwards, and have unweighted edges. The frontier-size rule matters more than it looks, because it is the only thing that protects you when one end of the search fans out and the other does not.

SOLVE IT YOURSELF

Solve it: search from both ends at once

A BFS to depth d explores bd nodes. Two searches meeting in the middle explore 2·bd/2 — for a branching factor of 10 and depth 6, that is a million nodes versus two thousand. Python or TypeScript.

YOUR TASK

Implement shortest_path_len(n, edges, src, dst) for an undirected, unweighted graph: return the number of edges on a shortest path, 0 if source equals target, or -1 if unreachable.

HINTS — 5 IDEAS
  1. Run two BFS frontiers — one from src, one from dst — each with its own distance map.
  2. Always expand the smaller frontier. That is what keeps the total explored count near 2·b^(d/2) instead of b^d.
  3. Expand a whole level at a time, not a single node, or the two frontiers desynchronise and the distances stop meaning what you think.
  4. When a neighbour is already in the other map, you have a candidate path of dist[u] + 1 + other[v].
  5. Do not return that immediately — finish the current level and take the minimum. Returning on first contact can overshoot the true shortest path by one, and that bug survives most casual testing. The tests here compare against a plain BFS on every pair.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done
NextEulerian Path: Every Edge, Once Next on the “Walking a graph” ladder · rung 4 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms