DSA interview question
A currency-exchange analyser models conversion costs as a directed graph whose weights can be negative (rebates), and needs shortest costs from a source. Dijkstra breaks with negative weights, so use Bellman–Ford. Relax every edge V − 1 times: a shortest path uses at most V − 1 edges, so after that many rounds every distance is correct. If a V-th round still improves something, a negative cycle is reachable, and shortest paths aren't defined.
Example: 3 vertices, edges 0→1 (5), 1→0 (3), 1→2 (−1), 2→0 (1), source 2 → [1, 6, 0].
vector<int> bellmanFord(int V, const vector<array<int, 3>>& edges, int S);
// unreachable -> 100000000; a negative cycle reachable from S -> {-1}
Input (V, edges, S) | Output | Explanation |
|---|---|---|
(3, [[0,1,5],[1,0,3],[1,2,-1],[2,0,1]], 2) | [1, 6, 0] | |
(2, [[0,1,9]], 0) | [0, 9] | |
(3, [[0,1,-2]], 0) | [0, -2, 100000000] | 2 is unreachable |
(3, [[0,1,1],[1,2,-3],[2,0,1]], 0) | [-1] | The cycle weight is −1 |
(1, [], 0) | [0] |
(Confirm: directed edges; weights may be negative; 10⁸ marks unreachable; the negative-cycle check only considers cycles reachable from S.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in