Show problems as
Classic problem #3488MediumArrayHash TableBinary Search

Closest Equal Element Queries

Real-world version: Nearest Twin Bay on the Carousel
Tracked in this browser only
Read Closest Equal Element Queries on LeetCode(opens in a new tab)

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

Python
def nearest_twin_steps(codes: list[int], asks: list[int]) -> list[int]:
Java
public List<Integer> nearestTwinSteps(int[] codes, int[] asks)