DSA
    advanced

    0-1 BFS (Deque Optimization)

    Software Engineer path · lesson 31 of 99
    time O(V + E)
    space O(V)

    Undirected; every weight must be 0 or 1.

    Try:
    Start node
    0110110A0B∞C∞D∞E∞
    dequeA
    SourcePoppedPushedIn dequeFinal

    Source A. 0-weight edges go to the front of the deque, 1-weight edges to the back.

    Code (running line highlighted)
    1. 1dist[src] = 0; deque = [src]
    2. 2while deque:
    3. 3 u = deque.popleft()
    4. 4 for (v, w) in edges(u): # w is 0 or 1
    5. 5 if dist[u] + w < dist[v]:
    6. 6 dist[v] = dist[u] + w; w == 0 ? push v to FRONT : push v to BACK
    Pops
    0 / 5
    Front pushes
    0 / 2
    Back pushes
    0 / 2
    Invariant: The deque is sorted by distance and holds at most two distinct values.

    Tap any element in the diagram to inspect its state at this step.

    1 / 11

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    Front or back of the deque?

    Sort

    Sort each case by where 0-1 BFS puts (or takes) the node.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    Front

    Drop items here

    Back

    Drop items here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    Why is 0-1 BFS faster than Dijkstra for 0-1 weight graphs?

    The short version

    Imagine walking through a city where some roads are free (weight 0) and others cost a toll (weight 1). With 0-1 BFS, free roads get priority in line, so you always take the cheapest path first.

    In more depth

    When Dijkstra is Overkill

    If edge weights are only 0 or 1, we don't need a full priority queue. A deque suffices!

    Algorithm:

    1.Start: push source to deque with distance 0
    2.Pop from FRONT (closest node)
    3.For weight-0 edges: push to FRONT (still closest)
    4.For weight-1 edges: push to BACK
    5.Visit each node at most once (shortest dist guaranteed)

    Why It Works:

    Deque maintains sorted order by distance because:

    Front has smallest distance
    Weight-0 keeps same distance (stays at front)
    Weight-1 increases distance by 1 (goes to back)

    Key Gotchas:

    Only works for 0 and 1 weights (or can be converted)
    Check if node already visited before processing
    Grid problems: 0 = free cell, 1 = obstacle to remove

    When to reach for this

    • Graph with edge weights 0 and 1 only
    • Grid where some moves are free and others cost 1
    • Obstacle removal on a grid
    • Keywords: 'minimum cost', 'binary weight edges'

    Interview Questions

    Google
    Amazon
    Meta
    Google
    Airbnb
    Bloomberg
    Microsoft
    Uber
    Netflix
    LinkedIn
    Palantir
    Amazon

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required