Ctrl K

Nearest Twin on a Ring

Medium
Lanterns stand along a circular walkway, and their colors are listed in colors: the last lantern is followed by the first one again. One step takes you to a neighbouring lantern in either direction, so the distance between positions i and j is the smaller of |i - j| and n - |i - j|, where n is the number of lanterns. You also get an array asks, where each entry is a lantern index (0-based). For every entry, find the distance to the nearest **other** lantern of the same color. If there is no such lantern, the answer is -1. Return the answers in the same order as the entries of asks.
Example 1
colors=[4, 7, 2, 4, 9, 7], asks=[0, 1, 4] → [3, 2, -1]

Lantern 0 (color 4): the other 4 is at position 3, three steps away either way. Lantern 1 (color 7): the other 7 is at position 5, four steps forward but only two going backwards 1 → 0 → 5. Color 9 appears once, so the answer is -1.

Example 2
colors=[5, 5, 5, 5], asks=[2, 3] → [1, 1]

Every lantern has a same-colored neighbour, so the distance is 1.

Example 3
colors=[8], asks=[0] → [-1]
Constraints
  • 1 ≤ len(asks) ≤ len(colors) ≤ 10⁵
  • 1 ≤ colors[i] ≤ 10⁶
  • 0 ≤ asks[i] < len(colors)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPairs With a Fixed Gap MediumWords Hidden in a Text MediumLongest Equal-Gap Chain MediumWeight by the Earliest Letter MediumA Value Shared by Every Row Medium
loading Python…
Input
colors=[4, 7, 2, 4, 9, 7], asks=[0, 1, 4]
Expected
[3, 2, -1]

Run checks the first 3 tests in your browser. Submit checks all 82 tests on the server, hidden ones included.