All problems
0666HardDepth-First SearchBreadth-First SearchGraph TheoryTopological SortKosaraju's AlgorithmTarjan's SCC Algorithm

Longest Loop in a Relay Network

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2360Longest Cycle in a Graph

This 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.

Examples

Example 1

Input
forward = [1, 0, 3, 4, 2, 6, -1]
Output
3

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

Input
forward = [1, 2, 3, 4, 5, 3]
Output
3

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

Input
forward = [1, 2, 3, 4, -1]
Output
-1

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.

Constraints

  • 2 <= forward.length <= 10^5
  • -1 <= forward[i] < forward.length
  • forward[i] != i

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def longest_relay_loop(forward: list[int]) -> int:
Java
public int longestRelayLoop(int[] forward)
September 7
Apply