Data Structures & Algorithms

Bellman-Ford Algorithm

Prepare for your coding interviews by mastering the Bellman-Ford algorithm. Our guide explains how to handle negative edge weights, detect negative cycles, and provides AI-powered practice.

Bellman-Ford Algorithm Implementation

Here is a Python implementation of the Bellman-Ford algorithm. This version also includes logic to detect negative cycles.


def bellman_ford(graph, start):
    # graph is a list of edges in the format (u, v, w)
    num_vertices = len(set(u for u, v, w in graph) | set(v for u, v, w in graph))
    distances = {i: float('Infinity') for i in range(num_vertices)}
    distances[start] = 0

    for _ in range(num_vertices - 1):
        for u, v, w in graph:
            if distances[u] != float('Infinity') and distances[u] + w < distances[v]:
                distances[v] = distances[u] + w

    # Check for negative weight cycles
    for u, v, w in graph:
        if distances[u] != float('Infinity') and distances[u] + w < distances[v]:
            return "Graph contains a negative weight cycle"

    return distances

                            

AI Coach Tip: The Bellman-Ford algorithm is slower than Dijkstra's (O(VE) vs O(E log V)), but its ability to handle negative weights makes it essential for certain problems. Always remember the two main phases: V-1 iterations of relaxation, followed by one final iteration to check for negative cycles.

Related Algorithm Guides

Explore more algorithm interview guides powered by AI coaching

Floyd Warshall Algorithm Interview Questions
AI-powered interview preparation guide
Topological Sort For Directed Acyclic Graphs Dags
AI-powered interview preparation guide
Quickselect Algorithm For Finding Kth Smallest Element
AI-powered interview preparation guide
Online Interview Etiquette And Preparation
AI-powered interview preparation guide