Jump Game IV - Problem

Given an array of integers arr, you are initially positioned at the first index of the array.

In one step you can jump from index i to index:

  • i + 1 where: i + 1 < arr.length.
  • i - 1 where: i - 1 >= 0.
  • j where: arr[i] == arr[j] and i != j.

Return the minimum number of steps to reach the last index of the array.

Notice that you can not jump outside of the array at any time.

Input & Output

Example 1 — Basic Teleportation
$ Input: arr = [100,-23,-23,404,100,23,23,23,3,404]
Output: 3
💡 Note: Start at index 0 (100) → Jump to index 4 (same value 100) → Jump to index 5 (23) → Jump to index 9 (404, last index). Total: 3 steps.
Example 2 — Adjacent Jumps
$ Input: arr = [7]
Output: 0
💡 Note: Already at the last index, so 0 steps needed.
Example 3 — Mixed Strategy
$ Input: arr = [7,6,9,6,9,6,9,7]
Output: 1
💡 Note: Start at index 0 (7) → Jump directly to index 7 (same value 7, which is the last index). Total: 1 step.

Constraints

  • 1 ≤ arr.length ≤ 5 × 104
  • -108 ≤ arr[i] ≤ 108

Visualization

Tap to expand
Jump Game IV: Three Jump Types100-23-2340410023Start1234EndRight Jump (+1)Teleport Jump (same value: 100)Left Jump (-1)Goal: Reach last index in minimum stepsBFS guarantees optimal solution
Understanding the Visualization
1
Input Array
Array with indices 0 to n-1, goal is to reach last index
2
Jump Types
Left (-1), Right (+1), or Teleport (same value)
3
Minimum Steps
Find shortest path using BFS
Key Takeaway
🎯 Key Insight: BFS with value-to-indices mapping enables O(1) teleportation lookups for optimal O(n) solution
Asked in
Facebook 15 Amazon 12 Google 8 Microsoft 6
67.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen