Member-only story
Leetcode 1345: Jump Game IV
In this Leetcode problem, we want to find the shortest path to the last element of the array following a few rules.
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.
The main idea is to do a BFS from the starting index. In order to store the edges for the graph for the last condition arr[i] == arr[j]
, we need to pre define a Map<Integer, Set<Integer>>
containing all the indices for each value valuesToIndices
.
Furthermore, we can notice that once a key of valuesToIndices
has been consumed in the BFS, we have visited or put in a queue all the indices from the mapped set, and we don’t need to consume that queue again. This is important because it makes the algorithm O(V)
instead of O(V + E)
where V
is the number of vertices in the graph, and E
is the number of edges in the graph.
Here is the complete code:
class Solution {
public int minJumps(int[] arr) {
int n = arr.length;
// initialize valuesToIndices
HashMap<Integer, Set<Integer>> valuesToIndices
=…