Detect a Reachable Negative Cycle
Company: Hive.Ai
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
# Detect a Reachable Negative Cycle
Given a directed weighted graph, determine whether a negative-weight cycle is reachable from a specified start vertex. A cycle is negative when the sum of its edge weights is less than zero.
Implement:
```python
def has_reachable_negative_cycle(
vertex_count: int,
edges: list[tuple[int, int, int]],
start: int,
) -> bool:
...
```
Each edge is `(source, destination, weight)`, vertices are numbered `0` through `vertex_count - 1`, and parallel edges and self-loops are allowed.
## Constraints and Clarifications
- A negative cycle in a disconnected component that cannot be reached from `start` does not count.
- Edge weights may be positive, zero, or negative.
- An unreachable distance must never participate in arithmetic relaxation.
- Return only a boolean, but be prepared to explain how to recover one witness cycle.
- Analyze time and space complexity in terms of vertices and edges.
## Hints
- Ask how many edge-relaxation rounds can improve a shortest simple path when no reachable negative cycle exists.
- Track whether any relevant value still changes after that bound.
- Test a negative self-loop, an unreachable negative cycle, and a graph with negative edges but no negative cycle.
Quick Answer: Detect whether a negative-weight cycle is reachable from a specified vertex in a directed graph. Apply bounded edge-relaxation rounds without performing arithmetic on unreachable distances, and explain complexity, disconnected cycles, self-loops, parallel edges, and witness recovery.
Given a directed weighted graph and a start vertex, return whether any negative-weight cycle is reachable from that start. Unreachable components must not influence the result; parallel edges and self-loops are allowed.
Constraints
- Vertices are numbered from 0 through vertex_count - 1.
- Edge weights are integers and may be negative.
- Only cycles reachable from start count.
- Parallel edges and self-loops are allowed.
Examples
Input: {'vertex_count':3,'edges':[(0,1,1),(1,2,-2),(2,1,1)],'start':0}
Expected Output: True
Explanation: A reachable cycle has total weight -1.
Input: {'vertex_count':4,'edges':[(0,1,2),(2,3,-2),(3,2,1)],'start':0}
Expected Output: False
Explanation: A disconnected negative cycle does not count.
Hints
- Initialize only the start distance as finite.
- After at most V-1 relaxation rounds, one more reachable improvement proves a negative cycle.