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 - BFS with Value Mapping INPUT Array with indices 0-9 100 [0] -23 [1] -23 [2] 404 [3] 100 [4] 23 [5] 23 [6] 23 [7] 3 [8] 404 [9] Value Mapping: 100 --> [0, 4] -23 --> [1, 2] 404 --> [3, 9] 23 --> [5, 6, 7] 3 --> [8] Jump Types: 1. i+1 (right neighbor) 2. i-1 (left neighbor) 3. Same value indices Start: index 0, Goal: index 9 ALGORITHM STEPS 1 Build Value Map Group indices by value 2 Initialize BFS Queue = [(0, 0)], visited = {0} 3 BFS Traversal Explore all 3 jump types 4 Return Steps When reaching index n-1 BFS Trace: Step 0: Start at idx 0 (val=100) Step 1: Jump to idx 4 (same val) 100 at [0] --> 100 at [4] Step 2: Jump to idx 3 (i-1) idx 4 --> idx 3 (val=404) Step 3: Jump to idx 9 (same val) 404 at [3] --> 404 at [9] GOAL! FINAL RESULT Optimal Path Found idx 0 100 +1 idx 4 100 +1 idx 3 404 +1 idx 9 404 Jump Sequence: 0 --> 4 --> 3 --> 9 (same) (left) (same) Output: 3 Minimum Steps Key Insight: BFS guarantees the shortest path in an unweighted graph. By treating array indices as nodes and the three jump types as edges, we find minimum steps. Pre-computing the value-to-indices map enables O(1) lookup for same-value jumps. Clear visited indices from map to avoid revisits. TutorialsPoint - Jump Game IV | BFS with Value Mapping Approach
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