Skip to contentKEEP THE CRAFTTHE SANCTUARY

Multi-source BFS

Put every unique source into distance-zero BFS, then assign each reachable node on first discovery. One shared queue finds minimum unweighted distance from any source.

1 practice exercise8 interview problems

Recognize it when Many starting nodes spread simultaneously through equal-cost edges.

Checking your account…

Multi-source BFS Code Labs

Make All Sources Compete at the Same Time

Seed all unique sources before removing any node from the queue. Each source starts at distance zero, so the first wave represents every origin simultaneously. Repeating BFS separately would calculate more information and multiply work when the question only wants the nearest origin.

Freeze the Current Layer Width

multi_source_layers records nodes by minimum edge distance. range(len(queue)) evaluates the queue width before that layer begins. Neighbors appended during those pops wait for the next outer iteration; draining the queue inside one layer would mix several distances into one result.

Trace Shared BFS Layers

Reference
from collections import deque

def multi_source_layers(adjacency,sources):
    queue=deque(); seen=set()
    for source in sources:
        if source not in seen: seen.add(source); queue.append(source)
    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 multi_source_layers(adjacency,sources). The graph is unweighted and all source and neighbor indices are valid. Return nodes grouped by minimum distance from any source, preserving source then neighbor order.

Public tests

  • Seed one shared zero layer

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

Trace Shared BFS Layers

from collections import deque

def multi_source_layers(adjacency,sources):
    queue=deque(); seen=set()
    for source in sources:
        if source not in seen: seen.add(source); queue.append(source)
    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

Expand Two Ends of a Chain Together

Predict multi_source_layers([[1],[0,2],[1,3],[2]], [0,3,0]). The repeated source 0 is removed before the first layer width is captured.

Step Executed statement State Why
1 if source not in seen: seen.add(source); queue.append(source) queue=[0,3]; seen={0,3} Both origins seed layer zero; the duplicate 0 is not queued.
2 for _ in range(len(queue)): current layer width=2 Exactly the two existing seeds belong to this layer.
3 node=queue.popleft(); layer.append(node) node=0; layer=[0]; queue=[3] FIFO expansion processes one distance-zero origin.
4 seen.add(neighbor); queue.append(neighbor) queue=[3,1]; seen={0,1,3} Neighbor 1 is first discovered at distance one and waits.
5 layers.append(layer) layers=[[0,3]]; queue=[1,2] Expanding origin 3 similarly schedules 2, then the zero layer closes.
6 layers.append(layer) layers=[[0,3],[1,2]]; queue=[] All neighbors of the distance-one nodes are already seen, ending the search.
Print Output
print(multi_source_layers([[1],[0,2],[1,3],[2]],[0,3,0])) [[0, 3], [1, 2]]

The returned order follows source order and then the stated neighbor order. Equal-distance nodes need no numeric sorting. Duplicate source entries are ignored, and an empty source list produces no layers.

First Discovery Fixes the Distance

In an unweighted graph, a path arriving from the current distance-d layer has length d+1. Any shorter path would have expanded earlier, so an unseen neighbor can receive its final distance immediately. Marking it before enqueueing also prevents two sources from scheduling the same node twice.

Compute Nearest-Source Distances

Reference
from collections import deque

def nearest_source_distances(adjacency,sources):
    distance=[-1]*len(adjacency); queue=deque()
    for source in sources:
        if distance[source]==-1: distance[source]=0; queue.append(source)
    while queue:
        node=queue.popleft()
        for neighbor in adjacency[node]:
            if distance[neighbor]==-1: distance[neighbor]=distance[node]+1; queue.append(neighbor)
    return distance
Practice

Implement nearest_source_distances(adjacency,sources). The graph is unweighted and all source and neighbor indices are valid. Return each node's shortest distance from any source, or -1 if unreachable; follow adjacency edges in their given direction.

Public tests

  • Assign distance on first discovery

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

Compute Nearest-Source Distances

from collections import deque

def nearest_source_distances(adjacency,sources):
    distance=[-1]*len(adjacency); queue=deque()
    for source in sources:
        if distance[source]==-1: distance[source]=0; queue.append(source)
    while queue:
        node=queue.popleft()
        for neighbor in adjacency[node]:
            if distance[neighbor]==-1: distance[neighbor]=distance[node]+1; queue.append(neighbor)
    return distance

This Lab returns -1 for nodes no source can reach. Its adjacency list may be directed: the result is distance from a source to the node. Finding distance from a node to a source instead requires reversed edges. With an undirected graph these two interpretations coincide.

Defend the Interview Choice and Cost

One traversal costs O(V+E+S), where S includes duplicate supplied seeds. The distance list, discovered set, queue and layer output are bounded by O(V). For a four-neighbor grid, V and E are both O(R*C), producing the familiar cell-count bound. Use a single-source BFS for one origin, repeated searches when each origin’s distances are required, and multi-source Dijkstra when edge costs differ; equal-cost BFS cannot settle weighted distances on first discovery.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Compute shared layers or nearest-source distances in an adjacency graphO(V+E+S)O(V+E+S)V counts nodes, E counts adjacency entries and S counts supplied source entries, including duplicates.

Space

O(V) for distances or seen, frontier, and layer output.

Assumptions

  • Each node is discovered at most once; each adjacency list is scanned at most once.
  • Layer tracing captures the initial queue length once per layer, keeping newly appended nodes in the next layer.
  • collections.deque supports efficient appends and pops at either end; a list pop(0) would shift remaining entries.

Invariants Worth Saying Aloud

  1. All unique sources enter the queue with distance zero before expansion starts.
  2. Queued nodes have nondecreasing minimum edge distance from the source set.
  3. A discovered node is assigned before enqueueing and cannot be scheduled again.

When To Use Or Avoid Multi-source BFS

Use It When

  • Every edge has equal unit cost and every source begins at distance zero.
  • A directed adjacency list asks for distance from sources, or an undirected graph makes the directions equivalent.

Choose Another Tool When

  • Different edge weights invalidate first-discovery optimality; use an appropriate weighted shortest-path algorithm.
  • The question needs distance to sources in a directed graph; reverse edges before running this outward traversal.

Common Pitfalls

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

Seeding only the first origin

A source left out of the zero layer can receive a positive distance or remain unreachable.

Prevent it: Initialize every unique origin before BFS expansion.

Avoid

for source in sources[:1]:
    distance[source]=0

Use instead

for source in sources:
    if distance[source]==-1:
        distance[source]=0

Draining new nodes into the current layer

A while queue loop continues into nodes just appended, collapsing distinct arrival times.

Prevent it: Freeze the layer width with range(len(queue)) before processing its nodes.

Avoid

while queue:
    node=queue.popleft()
    layer.append(node)
    for neighbor in adjacency[node]:
        if neighbor not in seen:
            seen.add(neighbor)
            queue.append(neighbor)

Use instead

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)

Overwriting a source with a later arrival

A neighbor may already be a distance-zero source. Unconditional assignment replaces its optimal value with a longer path.

Prevent it: Assign and enqueue only a still-undiscovered neighbor.

Avoid

distance[neighbor]=distance[node]+1

Use instead

if distance[neighbor]==-1:
    distance[neighbor]=distance[node]+1

Reviewed References

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