Ctrl K

Teleporting Between Matching Cells

Hard
A track is made of cells, and cell i shows the number marks[i]. You stand on cell 0 and want to reach the last cell. In one hop from cell i you may move: - to a neighbouring cell i + 1 or i - 1, if it exists; - to any other cell j that shows the same number: marks[j] == marks[i]. You can never leave the track. Return the smallest number of hops needed to reach the last cell.
Example 1
marks=[3, 8, 5, 8, 1, 3, 2, 9, 8, 4] → 3

Hop 0 → 1 (neighbour), 1 → 8 (both hold 8), 8 → 9 (neighbour): three hops. Two hops are not enough to reach cell 9.

Example 2
marks=[6, 2, 6, 2, 6] → 1

The first and last cells both hold 6, so a single hop is enough.

Example 3
marks=[42] → 0

We already stand on the last cell, so no hops are needed.

Constraints
  • 1 ≤ len(marks) ≤ 5 · 10⁴
  • -10⁸ ≤ marks[i] ≤ 10⁸
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Shuttle Boardings HardOne-Swap Word Families HardWhich Machine to Cure HardWhich Machine to Unplug HardEscape the Huge Grid Hard
loading Python…
Input
marks=[3, 8, 5, 8, 1, 3, 2, 9, 8, 4]
Expected
3

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