Skip to content
DeepForgeby svx
All problems
HardGraph Algorithmsgraph-127

Negative Cycle Path Extraction Lite

Problem

Extract one negative-weight cycle from a directed weighted graph, if any exists.

Run Bellman-Ford from a virtual source (all distances start at 0) and remember the predecessor of the last relaxed node. Walk n predecessors back to guarantee landing inside the cycle, then follow predecessors until returning to the start. Return the cycle as a node list starting and ending at the same node, or [] when there is no negative cycle. edges is a list of [u, v, w] triples.

Hint

Walking n predecessor steps from any relaxed node always lands inside the cycle.

Test cases

case 1
in: [3,[[0,1,1],[1,2,-2],[2,1,-2]]]
expected: [2,1,2]
case 2
in: [3,[[0,1,1],[1,2,2]]]
expected: []
case 3
in: [2,[[0,1,-1],[1,0,-1]]]
expected: [0,1,0]
case 4
in: [1,[]]
expected: []
case 5
in: [4,[[0,1,1],[2,3,-1],[3,2,-1]]]
expected: [2,3,2]
Starter codePython
def find_negative_cycle(n, edges):
    # Your code here
    pass

5 test cases · run your code against them in the editor