KatInterview

Negative Loop Reachable From a Source Vertex

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsgraphsbellman-fordnegative-cycle

Last updated

Decide whether a weighted directed graph has a negative-total cycle reachable from a given source vertex, using Bellman-Ford while ignoring unreachable regions.

You are given a directed graph with n vertices numbered 0 to n - 1. The graph is described by a list edges, where each entry [u, v, w] is a directed edge from u to v with integer weight w. You are also given a vertex source.

A negative loop is a closed walk that starts and ends at the same vertex along directed edges and whose weights add up to a value strictly less than zero. A self-loop [v, v, w] with w < 0 counts as a negative loop.

Return True if there is a negative loop that can be reached from source, and False otherwise.

A loop is reachable if source can get to at least one vertex on it by following directed edges. source can reach itself with no edges.

Rules:

  • Negative loops in parts of the graph that source cannot reach must be ignored.
  • A loop with total weight exactly 0 is not negative.
  • Parallel edges (same u and v) are allowed and are treated as separate edges.
  • Self-loops are allowed.
  • If edges is empty, the answer is False.

Return a boolean.

Constraints

  • 1 <= n <= 1000
  • 0 <= len(edges) <= 5000
  • 0 <= u, v < n and 0 <= source < n
  • -1000 <= w <= 1000
  • The graph may contain self-loops and parallel edges.

Examples

Example 1

Input: can_reach_negative_loop(3, [[0, 1, 1], [1, 2, -5], [2, 1, 2]], 0)

Output: True

Example 2

Input: can_reach_negative_loop(3, [[0, 1, 5], [1, 2, -10], [2, 0, 5]], 2)

Output: False

Example 3

Input: can_reach_negative_loop(3, [[0, 1, 5], [1, 2, -20], [2, 0, 5]], 2)

Output: True

Hints

Hint 1

Think about single-source shortest paths when negative weights are allowed. Which classic algorithm handles them and tells you when distances can never settle?

Hint 2

A shortest simple path uses at most n - 1 edges, so n - 1 rounds of relaxing every edge suffice if no negative loop is reachable. What does it mean if one more round can still improve something?

Hint 3

Start every distance at infinity except the source, and only relax an edge when its start vertex already has a finite distance. This keeps loops in unreachable regions from triggering a false positive.