DSA
    advanced

    0-1 BFS (Deque Optimization)

    0-1 BFS (Deque Optimization)

    Shortest path when edge weights are only 0 or 1. Uses deque instead of priority queue for O(V+E) instead of O(E log V). Critical for grid problems with obstacles.

    ⏱ O(V + E)
    💾 O(V)
    Ready
    01100110d=01d=∞2d=∞3d=∞4d=∞5d=∞
    Deque — FRONT (w=0 pushed here) | BACK (w=1 pushed here)
    FRONT
    0
    BACK
    --- free edge (w=0) → push FRONT— toll edge (w=1) → push BACK

    0-1 BFS: find shortest path from node 0. Start: dist[0]=0. Use deque (double-ended queue): weight-0 edges go to FRONT, weight-1 to BACK.

    50%
    Live Variables
    start0
    deque[0]

    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