WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Data Structures & Algorithms · Intermediate · question 36 of 100

Can you explain the Bellman-Ford algorithm and its use cases?

📕 Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers — PDF + EPUB for $5

The Bellman-Ford algorithm is a single-source shortest path algorithm that can be used to find the shortest path between a source vertex and all other vertices in a weighted directed graph. It is capable of handling negative edge weights, which makes it more versatile than the Dijkstra’s algorithm. However, its time complexity is higher than Dijkstra’s algorithm.

The basic idea behind the Bellman-Ford algorithm is to relax all edges in the graph repeatedly, starting from the source vertex, until no further improvements can be made. The algorithm maintains a distance array that stores the current shortest distance from the source vertex to each vertex in the graph. Initially, all distances are set to infinity except the source vertex, which is set to zero. In each iteration, the algorithm checks if any edge can be relaxed to improve the distance to its endpoint. If so, the distance is updated in the distance array. The algorithm repeats this process for V-1 iterations, where V is the number of vertices in the graph. If a shorter path is found in the V-th iteration, then the graph has a negative weight cycle.

Here is an example implementation of the Bellman-Ford algorithm in Java:

public class BellmanFord {
    public int[] bellmanFord(Graph graph, int source) {
        int[] distance = new int[graph.getVertices()];
        Arrays.fill(distance, Integer.MAX_VALUE);
        distance[source] = 0;

        for (int i = 0; i < graph.getVertices() - 1; i++) {
            for (Edge edge : graph.getEdges()) {
                int u = edge.getSource();
                int v = edge.getDestination();
                int weight = edge.getWeight();
                if (distance[u] != Integer.MAX_VALUE && distance[u] + weight < distance[v]) {
                    distance[v] = distance[u] + weight;
                }
            }
        }

        for (Edge edge : graph.getEdges()) {
            int u = edge.getSource();
            int v = edge.getDestination();
            int weight = edge.getWeight();
            if (distance[u] != Integer.MAX_VALUE && distance[u] + weight < distance[v]) {
                System.out.println("Graph contains negative weight cycle");
            }
        }

        return distance;
    }
}

In this implementation, the bellmanFord method takes as input a weighted directed graph and a source vertex. It initializes a distance array to store the current shortest distance from the source vertex to each vertex in the graph, and sets all distances to infinity except the source vertex, which is set to zero. It then iterates through the graph V-1 times, relaxing each edge in the graph to improve the distance to its endpoint. Finally, it checks for negative weight cycles by iterating through the edges one more time. The method returns the distance array.

The Bellman-Ford algorithm can be used in a variety of applications, such as finding the shortest path in a network, detecting negative weight cycles in a graph, and solving the shortest path problem in a road network. However, its time complexity of O(VE) makes it less efficient than other algorithms such as Dijkstra’s algorithm for certain use cases.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Data Structures & Algorithms interview — then scores it.
📞 Practice Data Structures & Algorithms — free 15 min
📕 Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers — PDF + EPUB for $5

All 100 Data Structures & Algorithms questions · All topics