Question bank › Dynamic Programming
Dsa Dynamic Programming Easy

Bellman-Ford Pathfinding

Implement the Bellman-Ford algorithm to find the shortest path from a source vertex to all other vertices in a weighted directed graph that may have negative weights. If there's a negative weight cycle reachable from the source, return 'Negative Cycle'. If the graph is valid, return the distances from the source to each vertex. Input Format: - The first line contains two integers n (1 ≤ n ≤ 100) and m (1 ≤ m ≤ 1000) - the number of vertices and edges respectively. - The following m lines each contain three integers u, v, w (0 ≤ u, v < n; -10000 ≤ w ≤ 10000) representing a directed edge from u to v with weight w. Output Format: - If there is a negative cycle, output 'Negative Cycle'. - Otherwise, output n space-separated integers, the shortest distances from the source vertex (0) to each vertex. Example: Input: 5 8 0 1 5 0 2 4 1 2 -3 1 3 2 2 1 -2 3 4 1 4 3 -3 4 2 2 Output: 0 5 3 7 8

Key concepts

dynamic_programminggraphpathfinding

Practise this out loud — free

Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.

🎙 Practise this question now
Part of InterviewLab's verified interview question bank. We show the prompt and concepts to practise with — never a copy-paste solution.