Loading content...
You are given an integer array arr representing a sequence of portals, where each position in the array corresponds to a portal with a unique identifier (the value at that position). You start at the first position (index 0) and your goal is to reach the last position (index arr.length - 1) using the minimum number of moves.
From any position i, you can perform one of the following three types of moves:
i + 1 (if i + 1 < arr.length)i - 1 (if i - 1 >= 0)j where arr[i] == arr[j] and i != j (positions with matching portal identifiers)The teleportation mechanic allows you to instantly travel between any two positions that share the same portal identifier, making certain paths significantly shorter than simple linear traversal.
Return the minimum number of moves required to reach the final position from the starting position.
Note: You cannot move outside the bounds of the array at any point during your traversal.
arr = [100,-23,-23,404,100,23,23,23,3,404]3Starting at index 0 (value 100), we can teleport to index 4 (also value 100). From index 4, we step backward to index 3 (value 404). Finally, from index 3, we can teleport to index 9 (also value 404), which is our destination. Total moves: 3.
arr = [7]0The starting position is already the destination. No moves are required.
arr = [7,6,9,6,9,6,9,7]1From index 0 (value 7), we can directly teleport to index 7 (also value 7), reaching the destination in a single move.
Constraints