Skip to contentKEEP THE CRAFTTHE SANCTUARY

Breadth-first Search

Explore reachable graph nodes in nondecreasing edge distance using a FIFO queue. Fix each distance on first discovery, separate level widths from newly appended children, and account for a wide frontier.

2 practice exercises9 interview problems

Recognize it when Every move has the same unit cost and the question asks for fewest moves.

Checking your account…

Breadth-first Search Code Labs

Explore One Distance Layer at a Time

Breadth-first search processes all states at distance (d) before any state at distance (d + 1). In an unweighted graph, the first discovery therefore gives a shortest edge distance.

Own the Queue Frontier

The queue contains discovered nodes whose outgoing edges are not fully processed. Capturing the queue length before a level loop isolates one layer even as children are appended behind it.

Trace BFS Layers

Reference
from collections import deque

def bfs_layers(adjacency, start):
    if start == -1: return []
    queue = deque([start])
    seen = {start}
    layers = []
    while queue:
        layer = []
        for _ in range(len(queue)):
            node = queue.popleft()
            layer.append(node)
            for neighbor in adjacency[node]:
                if neighbor not in seen:
                    seen.add(neighbor)
                    queue.append(neighbor)
        layers.append(layer)
    return layers
Practice

Implement bfs_layers(adjacency, start). Return reachable node indexes grouped by unweighted distance, preserving neighbor order. Use adjacency lists whose neighbor indices are valid vertices; start must be a valid vertex index or the explicit -1 no-source sentinel.

Public tests

  • Separate queue layers

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace BFS Layers

from collections import deque

def bfs_layers(adjacency, start):
    if start == -1: return []
    queue = deque([start])
    seen = {start}
    layers = []
    while queue:
        layer = []
        for _ in range(len(queue)):
            node = queue.popleft()
            layer.append(node)
            for neighbor in adjacency[node]:
                if neighbor not in seen:
                    seen.add(neighbor)
                    queue.append(neighbor)
        layers.append(layer)
    return layers

Freeze a Layer While Discovering the Next

The existing layer Lab has two parents of node 3 and one disconnected node. Predict the queue size before each outer iteration; it is not the number of elements after children are appended.

Step Executed statement State Why
Start queue = deque([start]); seen = {start}; layers = [] queue=[0], seen={0}, layers=[] Only the source is at distance zero.
Reset root layer layer = [] layer=[]; queue=[0] Each outer iteration starts a new result list before capturing its current queue width.
Capture root width for _ in range(len(queue)): one loop iteration fixed before enqueuing children The range is evaluated before the loop starts, so appended children wait for the next outer iteration.
Expand root node = queue.popleft(); layer.append(node); seen.add(neighbor); queue.append(neighbor); layers.append(layer) after root iteration: queue=[1, 2], seen={0, 1, 2}, layers=[[0]] The two neighbor iterations discover 1 then 2, and the completed layer is recorded.
Expand node 1 node = queue.popleft(); layer.append(node); seen.add(neighbor); queue.append(neighbor) after this iteration: layer=[1], seen includes 3, queue=[2, 3] Mark 3 when discovered, before node 2 can propose it again.
Expand node 2 node = queue.popleft(); layer.append(node) after this iteration: neighbor 3 skipped, layer=[1, 2], queue=[3] Two edges to 3 do not produce two copies.
Finish reachable layers node = queue.popleft(); layer.append(node); layers.append(layer) after final outer iteration: layers=[[0], [1, 2], [3]] Node 4 is disconnected and never belongs to a reachable layer.
Print Output
print(bfs_layers([[1, 2], [3], [3], [], []], 0)) [[0], [1, 2], [3]]

The distance Lab stores -1 for unreachable nodes. Keeping that sentinel separate from valid distance zero prevents empty or disconnected states from masquerading as a source.

Mark Visited on Enqueue

Mark a node when it enters the queue, not when it leaves. That prevents two parents in the same layer from enqueueing the same neighbor and keeps both work and memory bounded by vertices plus edges.

Find Unweighted Distances

Reference
from collections import deque

def shortest_distances(adjacency, start):
    distances = [-1] * len(adjacency)
    if start == -1: return distances
    distances[start] = 0
    queue = deque([start])
    while queue:
        node = queue.popleft()
        for neighbor in adjacency[node]:
            if distances[neighbor] == -1:
                distances[neighbor] = distances[node] + 1
                queue.append(neighbor)
    return distances
Practice

Implement shortest_distances(adjacency, start). Return a list of shortest edge distances, using -1 for unreachable nodes. Use adjacency lists whose neighbor indices are valid vertices; start must be a valid vertex index or the explicit -1 no-source sentinel.

Public tests

  • Assign first-discovery distance

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find Unweighted Distances

from collections import deque

def shortest_distances(adjacency, start):
    distances = [-1] * len(adjacency)
    if start == -1: return distances
    distances[start] = 0
    queue = deque([start])
    while queue:
        node = queue.popleft()
        for neighbor in adjacency[node]:
            if distances[neighbor] == -1:
                distances[neighbor] = distances[node] + 1
                queue.append(neighbor)
    return distances

Choose BFS or DFS

Choose BFS for shortest unweighted paths, minimum moves, or explicit level order. Choose DFS when branch completion, postorder aggregation, or lower frontier width matters. Both traverse reachable graphs in O(V + E); BFS may hold an entire wide layer.

Explain It in an Interview

Say: “The queue is ordered by distance. I mark on enqueue, so each node enters once, and first discovery fixes its shortest unweighted distance.” Mention disconnected nodes and multi-source initialization. Binary Tree Level Order(opens in a new tab) applies the same layer boundary to a tree.

Templates To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Tree level-order BFS

Freeze the level size, then pop that many.

You need to process a tree level by level.

Trigger words

  • level order
  • level by level
  • right side view
  • zigzag
  • minimum depth
  • serialize tree
from collections import deque

def level_order(root):
    if root is None:
        return []
    levels = []
    queue = deque([root])
    while queue:
        level = []
        for _ in range(len(queue)):     # exactly the nodes of this level
            node = queue.popleft()
            level.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        levels.append(level)
    return levels

Spot it when

  • 'Level order', 'right side view', 'zigzag'.
  • Minimum depth.

Remember

  • len(queue) at the start of the while body is the size of the current level.
  • Use deque.popleft(); list.pop(0) is O(n).

How problems bend it

  • Right side view: Keep only the last value of each level.
  • Zigzag order: Reverse every other level before adding it.

BFS shortest path

Mark on enqueue; each level is one step.

Every move costs the same and you want the fewest moves, or several sources spread at the same speed.

Trigger words

  • minimum steps
  • fewest moves
  • minimum minutes
  • unweighted shortest path
  • rotting
  • spreads every minute
  • word ladder
from collections import deque

def shortest_steps(graph, start, goal):
    queue = deque([start])
    visited = {start}
    steps = 0
    while queue:
        for _ in range(len(queue)):        # every node at distance `steps`
            node = queue.popleft()
            if node == goal:
                return steps
            for neighbor in graph[node]:
                if neighbor not in visited:
                    visited.add(neighbor)
                    queue.append(neighbor)
        steps += 1
    return -1

Spot it when

  • 'Minimum number of steps/moves/minutes'.
  • Unweighted graph or grid.
  • Rotting oranges, walls and gates.

Remember

  • The first time BFS reaches a node is along a shortest path.
  • Several starting points? Put all of them in the queue before the loop (multi-source BFS).

How problems bend it

  • Rotting oranges: Start with every rotten orange in the queue; each ring is one minute.
  • Word ladder: Neighbors are the words that differ by one letter.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Breadth-first Search proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Adjacency-list BFSO(V + E)O(V + E)Each reachable vertex enters once, and its outgoing edges are scanned once.

Space

O(V) visited/distances and queue; a tree queue can hold O(width) nodes.

Assumptions

  • Use deque.popleft rather than list.pop(0), which shifts remaining elements.
  • The graph visited set can dominate layer width; returned layer lists also store all reachable vertices.

Invariants Worth Saying Aloud

  1. The queue orders discovered nodes by nondecreasing shortest edge distance.
  2. A node receives its distance and enters the queue only on first discovery.
  3. A captured queue width processes only the current layer.

When To Use Or Avoid Breadth-first Search

Use It When

  • Use a FIFO queue for shortest unweighted paths or explicit levels.
  • Initialize all sources together at distance zero for nearest-source distance.

Choose Another Tool When

  • Weighted edges require a policy suited to their weights, such as 0-1 BFS or Dijkstra.
  • DFS can be simpler when only reachability or postorder is required.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Reusing unweighted distance for a heavier edge

Adding 1 to distance 0 for an edge of weight 7 reports 1, not the weighted path cost 7.

Prevent it: Treat this as a unit-edge algorithm; a weighted relaxation adds the actual weight under an appropriate frontier policy.

Avoid

candidate = distance + 1

Use instead

candidate = distance + weight

Omitting discovery marking before enqueue

Two parents can append the same unseen node when neither records it as discovered.

Prevent it: Add to seen in the same transition as enqueueing.

Avoid

for neighbor in neighbors:
    if neighbor not in seen: queue.append(neighbor)

Use instead

for neighbor in neighbors:
    if neighbor not in seen:
        seen.add(neighbor)
        queue.append(neighbor)

Popping the newest node instead of the oldest

pop returns 2 from [1,2], turning the queue policy into a stack and losing layer order.

Prevent it: Remove from the left with deque.popleft.

Avoid

node = queue.pop()

Use instead

node = queue.popleft()

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.