Python 3.11+
collections.deque supports efficient appends and pops at either end; a list pop(0) would shift remaining entries.
Verify in Python docs(opens in a new tab)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…
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.
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.
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 layersImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 layersPredict 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. |
| 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.
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.
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 distanceImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 distanceThis 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.
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 3.11+
collections.deque supports efficient appends and pops at either end; a list pop(0) would shift remaining entries.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Compute shared layers or nearest-source distances in an adjacency graph | O(V+E+S) | O(V+E+S) | V counts nodes, E counts adjacency entries and S counts supplied source entries, including duplicates. |
O(V) for distances or seen, frontier, and layer output.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
for source in sources[:1]:
distance[source]=0for source in sources:
if distance[source]==-1:
distance[source]=0Where you will hit this: Distance to the Nearest Source(opens in a new tab)
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.
while queue:
node=queue.popleft()
layer.append(node)
for neighbor in adjacency[node]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)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)Where you will hit this: Distance to the Nearest Source(opens in a new tab)
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.
distance[neighbor]=distance[node]+1if distance[neighbor]==-1:
distance[neighbor]=distance[node]+1Where you will hit this: Rotting Oranges(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-12
python-docs · checked 2026-07-27