Shortest Paths, MST & Flow · 15 min · free lesson

Bidirectional BFS: When to Use It

Recognise the problem shape before choosing Bidirectional BFS.

Core idea

Layer distances remain meaningful when the two searches meet. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Expand the smaller frontier from each endpoint until the visited sets meet.

O(b^(d/2)) frontier typical · O(V) space246 execution steps
main · before line 52Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputhit -> cog via [hot,dot,dog,lot,log,cog]

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 52
fn ladder_length(start: &str, goal: &str, words: &[&str]) -> usize {
    use std::collections::{HashMap, HashSet};
    // Every word after the start must come from the list, including the goal.
    if !words.contains(&goal) {
        return 0;
    }
    let mut front = HashSet::from([start.to_owned()]);
    let mut back = HashSet::from([goal.to_owned()]);
    let mut left = HashMap::from([(start.to_owned(), 1)]);
    let mut right = HashMap::from([(goal.to_owned(), 1)]);
    while !front.is_empty() && !back.is_empty() {
        if front.len() > back.len() {
            std::mem::swap(&mut front, &mut back);
            std::mem::swap(&mut left, &mut right);
        }
        let mut next = HashSet::new();
        let mut best = usize::MAX;
        for word in &front {
            if let Some(&d) = right.get(word) {
                best = best.min(left[word] + d - 1);
            }
            for &candidate in words {
                if candidate.len() != word.len()
                    || word
                        .bytes()
                        .zip(candidate.bytes())
                        .filter(|(a, b)| a != b)
                        .count()
                        != 1
                {
                    continue;
                }
                let d = left[word] + 1;
                if let Some(&other) = right.get(candidate) {
                    best = best.min(d + other - 1);
                }
                if !left.contains_key(candidate) {
                    left.insert(candidate.to_owned(), d);
                    next.insert(candidate.to_owned());
                }
            }
        }
        if best != usize::MAX {
            return best;
        }
        front = next;
    }
    0
}
 
fn main() {
    let result =
        ladder_length("hit", "cog", &["hot", "dot", "dog", "lot", "log", "cog"]).to_string();
    println!("{result}");
}

Try your own version

Compare the visible input `hit -> cog via [hot,dot,dog,lot,log,cog]` with `hit -> cog via [hot,dot]`. Predict why their results are `5` and `0`. Then change one legal value and explain whether the same invariant, layer distances remain meaningful when the two searches meet, still applies.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line. Borrowed or moved values are hidden when they cannot be inspected safely.
Five-panel Shortest Paths, MST & Flow infographic; panel 4 illustrates Bidirectional Bfs.
Bidirectional Bfs: follow panel 4 to see the operation, then trace this lesson's example.

Understand it

The ladder hit→hot→dot→dog→cog contains 5 words and 4 transformations. Search from both endpoints and expand the smaller frontier layer, comparing meeting distances. A goal missing from the list, or no connecting sequence, yields the explicit result 0.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Return the number of words in the shortest ladder from start to goal, counting both ends and changing one letter at a time. Every word after start must be in the list, including goal. Return 0 when goal is absent from the list or no ladder exists. The visible fixture is hit -> cog via [hot,dot,dog,lot,log,cog] and its example result is 5. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for Bidirectional BFS when it asks for unweighted shortest paths with one source and one target. Here the concrete task is: Return the number of words in the shortest ladder from start to goal, counting both ends and changing one letter at a time. Every word after start must be in the list, including goal. Return 0 when goal is absent from the list or no ladder exists. The visible input hit -> cog via [hot,dot,dog,lot,log,cog] is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Inspect weight signs and graph direction: non-negative shortest paths, negative edges, and zero-one weights support different algorithms. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Expand the smaller frontier from each endpoint until the visited sets meet. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? Edge weights change what a path means. State whether the objective is minimum distance, a spanning structure, or feasible flow before choosing state. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is O(b^(d/2)) frontier typical · O(V) space; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 5 and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Check disconnected vertices, parallel edges, zero weights, and whether an unreachable result has a defined representation. Use numeric types wide enough for distances, weights, or capacities. In shortest-path heap variants, skip stale queue entries and guard sentinel arithmetic. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

The pattern

Expand the smaller frontier from each endpoint until the visited sets meet.

When to use it: unweighted shortest paths with one source and one target

Complexity: O(b^(d/2)) frontier typical · O(V) space

Input: hit -> cog via [hot,dot,dog,lot,log,cog]

Read the code

fn ladder_length(start: &str, goal: &str, words: &[&str]) -> usize {
    use std::collections::{HashMap, HashSet};
    // Every word after the start must come from the list, including the goal.
    if !words.contains(&goal) {
        return 0;
    }
    let mut front = HashSet::from([start.to_owned()]);
    let mut back = HashSet::from([goal.to_owned()]);
    let mut left = HashMap::from([(start.to_owned(), 1)]);
    let mut right = HashMap::from([(goal.to_owned(), 1)]);
    while !front.is_empty() && !back.is_empty() {
        if front.len() > back.len() {
            std::mem::swap(&mut front, &mut back);
            std::mem::swap(&mut left, &mut right);
        }
        let mut next = HashSet::new();
        let mut best = usize::MAX;
        for word in &front {
            if let Some(&d) = right.get(word) {
                best = best.min(left[word] + d - 1);
            }
            for &candidate in words {
                if candidate.len() != word.len()
                    || word
                        .bytes()
                        .zip(candidate.bytes())
                        .filter(|(a, b)| a != b)
                        .count()
                        != 1
                {
                    continue;
                }
                let d = left[word] + 1;
                if let Some(&other) = right.get(candidate) {
                    best = best.min(d + other - 1);
                }
                if !left.contains_key(candidate) {
                    left.insert(candidate.to_owned(), d);
                    next.insert(candidate.to_owned());
                }
            }
        }
        if best != usize::MAX {
            return best;
        }
        front = next;
    }
    0
}

fn main() {
    let result =
        ladder_length("hit", "cog", &["hot", "dot", "dog", "lot", "log", "cog"]).to_string();
    println!("{result}");
}

Complete std-only bidirectional-bfs program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace Bidirectional BFS on input cat -> dog via [cot,cog,dog]. Which result follows from the documented contract?

Reveal the answer
  1. 5
  2. 4
  3. 3

For this input the result is 4. Layer distances remain meaningful when the two searches meet. Compare this independent fixture with the worked trace: The ladder hit→hot→dot→dog→cog contains 5 words and 4 transformations. Search from both endpoints and expand the smaller frontier layer, comparing meeting distances. A goal missing from the list, or no connecting sequence, yields the explicit result 0.

Go deeper

Common misconception: “A single arbitrary branch always gives the shortest ladder”

Layer distances remain meaningful when the two searches meet. The ladder hit→hot→dot→dog→cog contains 5 words and 4 transformations. Search from both endpoints and expand the smaller frontier layer, comparing meeting distances. A goal missing from the list, or no connecting sequence, yields the explicit result 0.

  1. Concrete transition: The ladder hit→hot→dot→dog→cog contains 5 words and 4 transformations. Search from both endpoints and expand the smaller frontier layer, comparing meeting distances. A goal missing from the list, or no connecting sequence, yields the explicit result 0.
  2. Independent second fixture: Input cat -> dog via [cot,cog,dog] produces 4. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input aaa -> bbb via [aab,abb,bbb] produces 4. Layer distances remain meaningful when the two searches meet. The stated work bound is O(b^(d/2)) frontier typical · O(V) space. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input hit -> cog via [hot,dot,dog,lot,log,cog] with hit -> cog via [hot,dot]. Predict why their results are 5 and 0. Then change one legal value and explain whether the same invariant, layer distances remain meaningful when the two searches meet, still applies.

Connections

  • Bidirectional BFS: Mental Model: Expand the smaller frontier from each endpoint until the visited sets meet.
  • Challenge: Bidirectional BFS: Return the number of words in the shortest ladder from start to goal, counting both ends and changing one letter at a time. Every word after start must be in the list, including goal. Return 0 when goal is absent from the list or no ladder exists.
Reveal the Algorithm Atlas answer

5

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Bidirectional BFS: When to Use It (courseId "algorithms", lessonId "algorithm.bidirectional-bfs.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.bidirectional-bfs.recognize
Goal: Layer distances remain meaningful when the two searches meet. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.bidirectional-bfs.recognize) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.