Closest Equal Element Queries
Real-world version: Nearest Twin Bay on the CarouselThe statement here is our own: the same inputs, outputs and technique.
A picking carousel has n storage bays bolted round a closed ring, numbered 0 to n - 1 in the order they sit on the ring, with bay n - 1 sitting right next to bay 0. Bay i holds the product coded codes[i]; the same code may be stocked in several bays.
One step of the carousel moves you from a bay to either of the two bays beside it, so it can be turned in either direction.
For every entry in asks, treat asks[j] as a starting bay and report the fewest steps from it to a different bay holding the same code. Report -1 for that entry when no other bay holds that code. Because a step count is never negative, -1 cannot be confused with a real answer.
Return the answers as a list in the same order as asks.
Examples
Example 1
- Input
- codes = [7, 2, 9, 2, 7], asks = [0, 1, 2]
- Output
- [1, 2, -1]
Bays 0 and 4 both hold code 7 and sit next to each other across the seam of the ring. Bays 1 and 3 both hold code 2. Code 9 is stocked once only.
Example 2
- Input
- codes = [7, 3, 3, 3, 7, 3, 3, 7], asks = [0, 7, 4]
- Output
- [1, 1, 3]
Code 7 sits in bays 0, 4 and 7. From bay 0 the nearest is bay 7, from bay 7 it is bay 0, and from bay 4 it is bay 7.
Example 3
- Input
- codes = [4, 4, 4], asks = [0, 1, 2]
- Output
- [1, 1, 1]
With only three bays and one code, every bay has a neighbour holding the same code one step away.
Constraints
- 1 <= asks.length <= codes.length <= 10^5
- 1 <= codes[i] <= 10^6
- 0 <= asks[j] < codes.length
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 nearest_twin_steps(codes: list[int], asks: list[int]) -> list[int]:public List<Integer> nearestTwinSteps(int[] codes, int[] asks)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 9 test cases: 9 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