Jump Game IV Problem
Description
LeetCode Problem 1345.
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 + 1where:i + 1 < arr.length.i - 1where:i - 1 >= 0.jwhere:arr[i] == arr[j]andi != 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.
Example 1:
Input: arr = [100,-23,-23,404,100,23,23,23,3,404]
Output: 3
Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.
Example 2:
Input: arr = [7]
Output: 0
Explanation: Start index is the last index. You do not need to jump.
Example 3:
Input: arr = [7,6,9,6,9,6,9,7]
Output: 1
Explanation: You can jump directly from index 0 to index 7 which is last index of the array.
Constraints:
1 <= arr.length <= 5 * 10^4-10^8 <= arr[i] <= 10^8
Solution
Approach: BFS, Using Each Value Once
Every jump costs one step, so the fewest steps to the last index is a shortest path in an unweighted graph: BFS from index 0. The neighbours of i are i - 1, i + 1, and every other index holding the same value. Group the indices by value in a hash map first, so the equal-value neighbours can be found without scanning the array.
The catch is the equal-value edges. With many equal values (say [1,1,1,...,1,2]), every one of those indices would walk the whole group again, which is O(n2). But the first time BFS reaches any index with value v, it queues all indices with value v at once. After that, the group can never give anything new, so remove the value from the map right after using it. Each group is then scanned only once in total.
BFS stops as soon as the last index is taken out of the queue; with one element the answer is 0 right away.
Complexity: O(n) time and space: every index is queued once and every value's group is scanned once.
from collections import defaultdict, deque
class Solution:
def minJumps(self, arr: List[int]) -> int:
n = len(arr)
same = defaultdict(list) # value -> every index holding it
for i, x in enumerate(arr):
same[x].append(i)
dist = [-1] * n
dist[0] = 0
queue = deque([0])
while queue:
i = queue.popleft()
if i == n - 1:
return dist[i]
# Neighbours, plus every index with the same value. Each value's list is used
# only once: after that all those indices are already in the queue.
for j in [i - 1, i + 1] + same.pop(arr[i], []):
if 0 <= j < n and dist[j] == -1:
dist[j] = dist[i] + 1
queue.append(j)
return -1 # not reached: the last index can always be reached