2
Here we are using map and queue3
map for storing the array elements and where are the other indices of the same element6
Initially we start with 0 index7
So we offer it to the queue8
Now until the queue is empty we have to do few things for a given position9
i> check the next index (i+1)10
ii> check the previous index(i-1)11
iii> check all the indices of the list whih are present in the map12
once these three things have been done we will13
remove the element that is arr[i]14
because if we did not remove it we are going to do the same repeated task over and over again15
and this will result in stack overflow16
so it is important to remove the indices which have been visited once17
every time we check the queue we incease the answer because viewing a queue means that18
we are not at the last index20
I hope the idea was clear :) you'll understand better when you see the code23
public int minJumps(int[] arr) {27
Map<Integer, List<Integer>> mp = new HashMap<>();28
for (int i = 0; i < arr.length; i++) {29
if (!mp.containsKey(arr[i])) {30
mp.put(arr[i], new ArrayList<>());32
List<Integer> ls = mp.get(arr[i]);35
// System.out.print(mp);36
Queue<Integer> q = new LinkedList<>();39
while (!q.isEmpty()) {42
for (int i = 0; i < size; i++) {45
if (j + 1 < n && mp.containsKey(arr[j + 1])) {46
if (j + 1 == n - 1) return ans;50
if (j - 1 > 0 && mp.containsKey(arr[j - 1])) {54
// adding list indices55
if (mp.containsKey(arr[j])) {56
for (int k : mp.get(arr[j])) {57
// if(k == n-1) return ans;59
if (k == n - 1) return ans;