Mark visited when you push or when you pop?

Graphs Mid-level Python 3.13+ Reviewed By Best Latest Apps

Predict the output

What does this print?

Python 3.13
from collections import deque
adj = {0: [1, 2, 3], 1: [4], 2: [4], 3: [4], 4: []}

def pushes(mark_on_push: bool) -> int:
    seen = {0}
    q = deque([0])
    count = 1
    while q:
        u = q.popleft()
        if not mark_on_push:
            seen.add(u)
        for v in adj[u]:
            if v not in seen:
                if mark_on_push:
                    seen.add(v)
                q.append(v)
                count += 1
    return count

print(pushes(True), pushes(False))

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 5 7

Right: marking on pop lets node 4 be queued three times.

Marking on push caps queue entries at one per node, which is what keeps BFS at O(V + E).

Why not the others?
  • B 5 5. Node 4 has three parents, and with marking on pop each one queues it.
  • C 7 5. Marking on push is the version that queues each node once.

30-second answer

Mark on push for BFS. If you mark on pop, a node can be added to the queue once per neighbour before it is ever popped, so the queue can grow to O(E) entries and do repeated work. Marking on push guarantees each node enters the queue once. Dijkstra is the exception: it settles nodes on pop and skips stale entries instead.

Practise saying it · 30 s. No recording, just a timer

Explain when to mark nodes visited.

Say your answer out loud, then check which of these points you covered:

  • BFS: on push
  • Dijkstra: settle on pop
  • Why it matters for cost

Deep dive

For DFS with an explicit stack, marking on pop is common and still correct, but the stack may hold duplicates.

In grid searches, marking on push is what keeps the cost at O(R·C).

The Dijkstra rule is about correctness: a node's best distance is only known when it is popped.

Common mistakes

  • Marking on pop in BFS and wondering why the queue explodes on dense graphs.
  • Marking on push in Dijkstra, which can lock in a distance that is not the shortest.

Senior take & follow-ups

Say 'mark on push for BFS, settle on pop for Dijkstra'. It covers both cases in one line.

Follow-up questions

Think of your answer first, then open the hint.

  1. Does marking on pop ever give wrong BFS distances?

    Show hint

    Distances stay right if you check on pop, but work and memory grow.

  2. What about A*?

    Show hint

    Like Dijkstra: settle on pop, with a heuristic added to the priority.

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.