Jump Game IV

Hard

Topics
ArrayBFSHash Table

Given an integer array nums, you start at index 0. From index i you can move to i+1, i-1, or any index j with nums[j] == nums[i] (all within bounds). Return the minimum number of steps to reach the last index.

Example 1

1000-231-23240431004235236237384049
Input:  nums = [100,-23,-23,404,100,23,23,23,3,404]
Output: 3

Example 2

70
Input:  nums = [7]
Output: 0

Example 3

7061926394659677
Input:  nums = [7,6,9,6,9,6,9,7]
Output: 1

Constraints

  • 1 <= nums.length <= 5*10^4
  • -10^8 <= nums[i] <= 10^8
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every move costs one step, so this is breadth-first search over indices. The twist is the value-teleport edge: from i you can reach every index sharing nums[i], which makes the implicit graph dense — a value appearing m times contributes m² edges.

The fix is the whole problem. Group indices by value up front, and delete a value's bucket the first time it is used. Once BFS has expanded one index of a value, every index with that value is already enqueued at the current distance, so the bucket can never help again.

Without that deletion the same bucket is rescanned from every member. On an array of 20,000 equal elements, clearing the bucket costs 19,999 index visits; not clearing costs 399,960,001 — measured, a factor of 20,000. The answer is identical either way, which is what makes this a trap rather than a bug.

Approach

  1. Build a map from value to the list of indices holding it.
  2. BFS from index 0, expanding one distance layer at a time.
  3. On visiting an index, return the current distance if it is the last index.
  4. Enqueue every unvisited index in its value bucket, then delete the bucket.
  5. Enqueue i-1 and i+1 if unvisited.

Dry Run

nums = [100,-23,-23,404,100,23,23,23,3,404]

value buckets
  100: [0,4]   -23: [1,2]   404: [3,9]   23: [5,6,7]   3: [8]

  layer  indices reached
  0      [0]
  1      [4, 1]          teleport to the other 100, and step to index 1
  2      [5, 3, 2]
  3      [6, 7, 9]       index 9 is the last index

answer 3

Complexity

  • Time — O(n): each index is visited once, and each value bucket is scanned once because it is deleted afterwards. Summing bucket sizes over all values is n, so the teleport edges cost O(n) in total rather than O(n²).
  • Space — O(n) for the buckets, the visited flags and the queue.

Common Pitfalls

  • Not deleting the bucket after use. Measured above: 399,960,001 index visits instead of 19,999 on an array of 20,000 equal values. The result stays correct, so tests pass and the submission times out.
  • Marking visited on dequeue rather than enqueue. With dense teleport edges the same index is queued many times over, which reintroduces the blow-up the bucket deletion was meant to remove.
  • Using depth-first search. Steps are unweighted, so only BFS gives the minimum.
  • Reaching for Dijkstra. All edges weigh 1, which is exactly when BFS is already optimal.
  • Forgetting the single-element case, where the start is already the last index and the answer is 0.
  • Deleting the bucket before enqueueing from it, which loses every teleport for that value.
  • Checking the target only when enqueueing rather than when dequeueing, or vice versa, and getting the distance off by one. Returning on dequeue with the layer counter is the version that lines up.

Full Solution — all languages

class Solution:
    def minJumps(self, nums):
        arr = nums
        n = len(arr)
        if n <= 1:
            return 0
        from collections import defaultdict, deque
        val = defaultdict(list)
        for i, x in enumerate(arr):
            val[x].append(i)
        visited = [False] * n
        visited[0] = True
        q = deque([0])
        steps = 0
        while q:
            for _ in range(len(q)):
                idx = q.popleft()
                if idx == n - 1:
                    return steps
                if arr[idx] in val:
                    for j in val[arr[idx]]:
                        if not visited[j]:
                            visited[j] = True
                            q.append(j)
                    del val[arr[idx]]
                for nb in (idx + 1, idx - 1):
                    if 0 <= nb < n and not visited[nb]:
                        visited[nb] = True
                        q.append(nb)
            steps += 1
        return -1
SensAI
Beta
Tap the mic to stop voice mode