Trains the technique from
LeetCode 2360Longest Cycle in a GraphThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A packet network has stations numbered 0 to n - 1. Each station hands every packet it receives to at most one other station: forward[i] is the station that station i hands to, and forward[i] = -1 means station i keeps what it receives and hands on nothing. No station hands to itself.
A loop is a list of distinct stations s[0], s[1], ..., s[L-1] with L >= 2 where each station hands to the next one, forward[s[j]] = s[j + 1] for every j below L - 1, and the last hands back to the first, forward[s[L-1]] = s[0]. The length of that loop is L, the number of stations on it.
Return the length of the longest loop in the network, or -1 if no loop exists.
Example 1
Stations `2, 3, 4` hand on in a ring, which is a loop of three. Stations `0` and `1` hand to each other, a loop of two. Station `5` hands to `6`, which hands on nothing.
Example 2
Stations `3, 4, 5` form a loop of three. Stations `0, 1, 2` lead into it but nothing hands back to them, so they are on no loop.
Example 3
Every packet travels forward to station `4` and stops there. No station is ever handed back to, so there is no loop and the sentinel is returned.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def longest_relay_loop(forward: list[int]) -> int:public int longestRelayLoop(int[] forward)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.