All problems
0778MediumArrayHash TableTwo PointersFloyd's Cycle Finding Algorithm

Same Way Round The Docking Ring

Tracked in this browser only
Write code

Trains the technique from

LeetCode 457Circular Array Loop

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 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:

  1. it touches two or more distinct bays, so a bay whose shunt lands on itself does not count; and
  2. 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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def circular_array_loop(offsets: list[int]) -> bool:
Java
public boolean circularArrayLoop(int[] offsets)
September 7
Apply