Circular Array Loop
Real-world version: Same Way Round The Docking RingThe statement here is our own: the same inputs, outputs and technique.
A cargo terminal has n docking bays laid out in a ring and numbered 0 to n - 1, with bay n - 1 sitting next to bay 0. Bay i carries a shunt value offsets[i], and a trolley standing at bay i is always shunted to bay (i + offsets[i]) mod n: a positive value pushes it that many bays forward round the ring, a negative value pulls it that many bays backward, and the ring wraps in both directions. A shunt value is never 0, and its size may be larger than n, in which case the trolley goes all the way round one or more times.
A round trip is a starting bay such that following the shunts from it eventually brings the trolley back to that same bay. A round trip counts only if both of these hold:
- it touches two or more distinct bays, so a bay whose shunt lands on itself does not count; and
- every shunt it uses points the same way, so either all of them are positive or all of them are negative.
Return true if at least one bay starts a round trip that counts, and false otherwise.
Examples
Example 1
- Input
- offsets = [1,6,2,1,4,1]
- Output
- true
Starting at bay 2 the trolley is shunted to bay 4, and bay 4 shunts it 4 forward which wraps back to bay 2. That round trip touches two distinct bays and both shunts point forward, so it counts.
Example 2
- Input
- offsets = [5,-5,5,-5]
- Output
- false
Bays 0 and 1 shunt to each other, and so do bays 2 and 3, but each of those round trips uses one forward shunt and one backward shunt, so neither counts.
Example 3
- Input
- offsets = [4,4,4,4]
- Output
- false
Every bay shunts the trolley a full lap round the ring and back onto itself, so each round trip here touches only one bay.
Constraints
- 1 <= offsets.length <= 5000
- -1000 <= offsets[i] <= 1000
- offsets[i] != 0
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def circular_array_loop(offsets: list[int]) -> bool:public boolean circularArrayLoop(int[] offsets)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 17 test cases: 17 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's