LeetCode 1345. Jump Game IV
Question
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]
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:
1 | Input: arr = [100,-23,-23,404,100,23,23,23,3,404] |
Example 2:
1 | Input: arr = [7] |
Example 3:
1 | Input: arr = [7,6,9,6,9,6,9,7] |
Constraints:
1 <= arr.length <= 5 * 104
-108 <= arr[i] <= 108
Source: https://leetcode.com/problems/jump-game-iv/
Solution
The idea of using queue size is to achieve layer-order traversal, like LeetCode 102. Binary Tree Level Order Traversal. So we can record the length of current search paths easily.
Repeated visits to nodes with the same value are not helpful in getting the min number of steps to the end. Thus, we can prune the BFS tree. Note that marking those nodes as visited is not enough. We need to clear corresponding key-value pair in the valueIndexMap
. Because as long as these nodes are pushed to the queue, they will increase time cost.
1 | public int minJumps(int[] arr) { |
LeetCode 1345. Jump Game IV