Jump Game IV

Given an array of integers arr, you start at index 0. In one step you can jump from index i to i + 1, to i - 1, or to any index j != i with arr[j] == arr[i], as long as you stay inside the array. Return the minimum number of steps to reach the last index.

30:00

Jump Game IV
hard
Free written solution
Topics
Companies

Given an array of integers arr, you start at index 0. In one step you can jump from index i to i + 1, to i - 1, or to any index j != i with arr[j] == arr[i], as long as you stay inside the array. Return the minimum number of steps to reach the last index.

Example 1:
Input: {"arr":[100,-23,-23,404,100,23,23,23,3,404]}
Output: 3
Constraints:
  • 1≤arr.length≤5×1041 \leq \text{arr.length} \leq 5 \times 10^4

  • −108≤arr[i]≤108-10^8 \leq \text{arr}[i] \leq 10^8

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr":[100,-23,-23,404,100,23,23,23,3,404]}

Start BFS at index 0. Each index links to its two neighbours and to every other index holding the same value, so BFS level = number of jumps.

1000L0-231-23240431004235236237384049

⌒ step to i ± 1 (above)

⌣ teleport to same value (below)

⇢ already reached

▢ last index

teleport groups (deleted after first use)

100 → [0, 4]

-23 → [1, 2]

404 → [3, 9]

23 → [5, 6, 7]

next level queue (1)

0

jumps / reached

0 / 1

Variables
VariableValue
n10
steps0
i-
queue1
DepthFunction Call
Stack empty
0/13