DSA
    advanced

    Bellman-Ford Algorithm

    Bellman-Ford Algorithm

    Find shortest paths from a source to all vertices, even with negative edge weights. Can also detect negative weight cycles.

    ⏱ O(VE)
    💾 O(V)
    Ready
    Iteration: 0

    Initialize: source node 0 has distance 0, all others are ∞

    50%
    Live Variables
    source0
    distances0,∞,∞,∞,∞

    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