from typing import List, Dict, Set, Deque
from collections import deque
class Solution:
int, List[int]]
m: Dict[int]
q: Deque[int, int]
distances: Dict[int]
arr: List[
def __init__(self):
self.m = dict()
self.q = deque()
self.distances = dict()
def minJumps(self, arr: List[int]) -> int:
# edge cases
if len(arr) < 3:
return len(arr) - 1
self.arr = arr
self.buildM()
= self.pickNext(0)
result while len(self.q) > 0:
if result is not None:
break
= self.q.popleft()
position = self.pickNext(position)
result return result if result is not None else 0
def compressInput(self, arr: List[int]) -> List[int]:
= [arr[0]]
result for i in range(1, len(arr)-1):
if arr[i] != arr[i-1] or arr[i] != arr[i+1]:
result.append(arr[i])-1])
result.append(arr[return result
def buildM(self):
for (i, x) in enumerate(self.arr):
= self.m.setdefault(x, [])
ml
ml.append(i)
def pickNext(self, pos: int) -> None | int:
= reversed(self.m.get(self.arr[pos], []))
ml self.m[self.arr[pos]] = []
= self.distances.get(pos,0)
distance
= []
nearest if pos < len(self.arr) - 1:
+ 1)
nearest.append(pos if pos > 0:
- 1)
nearest.append(pos
for t in [ml, nearest]:
for p in t:
if p not in self.distances:
if p >= len(self.arr) - 1:
return distance + len(self.arr) - p
self.q.append(p)
self.distances[p] = distance + 1
Jumps Game
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] and i != 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.
BFS Solution
BFS seems like a straghtforward way to do it since we are searching for the shortest way in the graph. We will require: - a function that pickes next steps based on the roles (back, forward, jump) - for picking where to jump we will use a mapping from values into their positions int -> [int] - a simple que of next steps - in order to avoid cycles we need another hash of visited positions we will also use it to retrace our steps