High interview relevanceRoadmap: Intermediate
TimeO(V + E)
SpaceO(V)

Why it costs this much

Each vertex is enqueued once, and each edge is examined once when its endpoint is dequeued.

Code

from collections import deque
def bfs(graph, start):
    seen, q = {start}, deque([start])
    while q:
        u = q.popleft()               # each vertex leaves the queue once
        for v in graph[u]:            # each edge is scanned once overall
            if v not in seen:
                seen.add(v)           # mark on enqueue
                q.append(v)
    return seen

Common pitfalls

Mark vertices as visited when you enqueue them, not when you dequeue them, or duplicates flood the queue. With an adjacency matrix the cost is O(V²).

Operation by operation

OperationBestAverageWorstSpace
Breadth-first searchO(V + E)O(V + E)O(V + E)O(V)

Breadth-first search. Adjacency list. Stops early only if you return when the target is found. With an adjacency matrix, enumerating neighbors makes it O(V²).

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list