DSA
    advanced

    Bellman-Ford Algorithm

    Software Engineer path · lesson 25 of 99
    time O(VE)
    space O(V)

    Directed and weighted; negative weights allowed, like A>B -2.

    Try:
    Start node
    Stop early when a pass changes nothing
    45-3-226A∞B∞C∞D∞S0

    Pass 1 · badges show the current distance from the source.

    SourceEdge tailImprovedChecked, no changeShortest-path edgeNegative cycle

    Source S: distance 0, everything else ∞.

    Code (running line highlighted)
    1. 1dist[src] = 0; dist[others] = ∞
    2. 2repeat n - 1 times:
    3. 3 for (u, v, w) in edges:
    4. 4 if dist[u] + w < dist[v]: dist[v] = dist[u] + w
    5. 5 (stop early if nothing changed)
    6. 6for (u, v, w) in edges: if dist[u] + w < dist[v]: negative cycle
    Relaxations tried
    0 / 18
    Improvements
    0 / 7

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

    1 / 24

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

    Run Bellman-Ford

    Sequence

    Order the phases of the algorithm.

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

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    Why does Bellman-Ford run V-1 iterations?

    The short version

    Imagine rumor spreading in a social network. Each round, everyone tells their neighbors what they've heard. After enough rounds, the shortest path (fewest retellings) stabilizes. Unlike Dijkstra, it works even if some rumors 'reduce' distance (negative weights).

    In more depth

    Edge Relaxation

    For each edge (u, v, weight):

    if dist[u] + weight < dist[v]:
        dist[v] = dist[u] + weight

    Algorithm

    1.Initialize: dist[source] = 0, all others = ∞
    2.Repeat V-1 times: Relax ALL edges
    3.Negative cycle check: If any edge can still be relaxed, negative cycle exists

    When to Use

    Graph has negative weights (Dijkstra fails)
    Need to detect negative cycles
    Simpler to implement than Dijkstra (no priority queue)

    When to reach for this

    • Shortest path with negative edges
    • Need to detect negative cycles
    • Limited number of edges/hops allowed
    • Arbitrage detection in currency exchange

    Interview Questions

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

    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