Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Shortest distances with negative edges

Medium · Target 20 minutes · Graphs

A directed graph has n nodes numbered 0 to n − 1. Each triple [u, v, w] in edges is an edge from u to v of weight w, which may be negative.

  • If a cycle of negative total weight can be reached from src, return an empty list.
  • Otherwise return a list whose entry v is the smallest total weight of a path from src to v, using 1000000000 (10⁹) for nodes that cannot be reached.

Examples

InputOutputWhy
n = 3, edges = [[0,1,2],[0,2,5],[2,1,-4]], src = 0[0, 1, 5]Through 2 is cheaper than direct: 5 − 4 = 1.
n = 4, edges = [[0,1,1],[1,2,2],[2,3,-6],[3,1,3]], src = 0[]1 → 2 → 3 → 1 totals −1 and is reachable from 0.
n = 4, edges = [[1,2,-1],[2,1,-1],[0,3,2]], src = 0[0, 1000000000, 1000000000, 2]There is a negative cycle, but 0 cannot reach it.

Constraints

  • 1 ≤ n ≤ 500
  • 0 ≤ edges.length ≤ 5000
  • −10⁴ ≤ w ≤ 10⁴

Hints

Hint 1

Relax every edge, in any order, n − 1 times. A shortest path has at most n − 1 edges.

Hint 2

Never relax an edge out of a node whose distance is still infinite: ∞ plus a negative weight is still ∞.

Hint 3

After n − 1 rounds, try one more. If any edge still improves a distance, a negative cycle is reachable.

Where people lose marks

  • Relaxing from a node at infinity: with a sentinel like 10⁹, adding a negative weight produces a "distance" below the sentinel for a node that was never reached.
  • Reporting a negative cycle anywhere in the graph rather than only one reachable from the source.
  • Running exactly n − 1 rounds and skipping the check round.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.