Welcome to Subscribe On Youtube
Question
Formatted question description: https://leetcode.ca/all/1345.html
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:
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 * 104
-108 <= arr[i] <= 108
Algorithm
Reference: https://leetcode.com/problems/jump-game-iv/solution/
- store nodes with the same value together in a graph dictionary
First loop over arr
to obtain each element and the indices at which the element is in arr
. Then loop over arr
again to obtain the next indices of each index.
Use dynamic programming. Starting from index 0, each time find the next possible indices that can be jumped to, and update the indices’ minimum jumps. Repeat the process until the last index is reached, and return the number of jumps to reach the last index.
To reduce runtime, consider some special cases first. If arr.length == 1
, then the first index is also the last index, so return 0. If the elements at the first index and the last index are the same, then jump once to the last index, so return 1. If the elements at the first index and the second last index are the same, then jump once to the second last index and jump another time to the last index, so return 2.
Code
-
class Solution { public int minJumps(int[] arr) { int n = arr.length; if (n <= 1) { return 0; } // store nodes with the same value together in a graph dictionary Map<Integer, List<Integer>> graph = new HashMap<>(); for (int i = 0; i < n; i++) { graph.computeIfAbsent(arr[i], v -> new LinkedList<>()).add(i); } List<Integer> curs = new LinkedList<>(); // store current layer curs.add(0); Set<Integer> visited = new HashSet<>(); int step = 0; // when current layer exists while (!curs.isEmpty()) { List<Integer> nex = new LinkedList<>(); // iterate the layer for (int node : curs) { // check if index 'node' reached end index if (node == n - 1) { return step; } // 1. check same value for (int child : graph.get(arr[node])) { if (!visited.contains(child)) { visited.add(child); nex.add(child); } } // clear the list to prevent redundant search graph.get(arr[node]).clear(); // 2. check left/right neighbors if (node + 1 < n && !visited.contains(node + 1)) { visited.add(node + 1); nex.add(node + 1); } if (node - 1 >= 0 && !visited.contains(node - 1)) { visited.add(node - 1); nex.add(node - 1); } } curs = nex; step++; } return -1; } } ############ class Solution { public int minJumps(int[] arr) { Map<Integer, List<Integer>> idx = new HashMap<>(); int n = arr.length; for (int i = 0; i < n; ++i) { idx.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i); } Deque<int[]> q = new LinkedList<>(); Set<Integer> vis = new HashSet<>(); vis.add(0); q.offer(new int[] {0, 0}); while (!q.isEmpty()) { int[] e = q.pollFirst(); int i = e[0], step = e[1]; if (i == n - 1) { return step; } int v = arr[i]; ++step; for (int j : idx.getOrDefault(v, new ArrayList<>())) { if (!vis.contains(j)) { vis.add(j); q.offer(new int[] {j, step}); } } idx.remove(v); if (i + 1 < n && !vis.contains(i + 1)) { vis.add(i + 1); q.offer(new int[] {i + 1, step}); } if (i - 1 >= 0 && !vis.contains(i - 1)) { vis.add(i - 1); q.offer(new int[] {i - 1, step}); } } return -1; } }
-
// OJ: https://leetcode.com/problems/jump-game-iv/ // Time: O(N) // Space: O(N) class Solution { public: int minJumps(vector<int>& A) { unordered_map<int, vector<int>> m; int N = A.size(), step = 0; for (int i = 0; i < N; ++i) m[A[i]].push_back(i); vector<bool> seen(N); seen[0] = true; queue<int> q{ {0} }; while (q.size()) { int cnt = q.size(); while (cnt--) { int u = q.front(); q.pop(); if (u == N - 1) return step; if (u - 1 >= 0 && !seen[u - 1]) { q.push(u - 1); seen[u - 1] = true; } if (u + 1 < N && !seen[u + 1]) { q.push(u + 1); seen[u + 1] = true; } if (m.count(A[u])) { for (int v : m[A[u]]) { if (seen[v]) continue; seen[v] = true; q.push(v); } m.erase(A[u]); } } ++step; } return -1; } };
-
''' list.remove(v): for list, remove by value, the first occurrence of v del my_dict[v]: for dict, delete by key 'v' my_dict = {'a': 1, 'b': 2, 'c': 3} del my_dict['b'] print(my_dict) # {'a': 1, 'c': 3} my_dict.pop('b') my_dict = {'a': 1, 'b': 2, 'c': 3} val = my_dict.pop('b') print(my_dict) # {'a': 1, 'c': 3} print(val) # 2 my_dict.popitem() my_dict = {'a': 1, 'b': 2, 'c': 3} item = my_dict.popitem() print(my_dict) # {'a': 1, 'b': 2} print(item) # ('c', 3) filter() and lambda my_dict = {'a': 1, 'b': 2, 'c': 3} my_dict = dict(filter(lambda item: item[0] != 'b', my_dict.items())) print(my_dict) # {'a': 1, 'c': 3} ''' from collections import deque class Solution: def minJumps(self, arr: List[int]) -> int: idx = defaultdict(list) for i, v in enumerate(arr): idx[v].append(i) q = deque([(0, 0)]) # (index, step) vis = {0} while q: i, step = q.popleft() if i == len(arr) - 1: return step v = arr[i] step += 1 for j in idx[v]: if j not in vis: vis.add(j) q.append((j, step)) # without this del, it will be huge/duplicated loop # over time limit for input [7,7,7,7,7,....7,7] del idx[v] # avoid dedup if i + 1 < len(arr) and (i + 1) not in vis: vis.add(i + 1) q.append((i + 1, step)) if i - 1 >= 0 and (i - 1) not in vis: vis.add(i - 1) q.append((i - 1, step)) ############ class Solution: def minJumps(self, arr: List[int]) -> int: idx = defaultdict(list) for i, v in enumerate(arr): idx[v].append(i) q = deque([(0, 0)]) vis = {0} while q: i, step = q.popleft() if i == len(arr) - 1: return step v = arr[i] step += 1 for j in idx[v]: if j not in vis: vis.add(j) q.append((j, step)) del idx[v] if i + 1 < len(arr) and (i + 1) not in vis: vis.add(i + 1) q.append((i + 1, step)) if i - 1 >= 0 and (i - 1) not in vis: vis.add(i - 1) q.append((i - 1, step))
-
func minJumps(arr []int) int { idx := map[int][]int{} for i, v := range arr { idx[v] = append(idx[v], i) } vis := map[int]bool{0: true} type pair struct{ idx, step int } q := []pair{ {0, 0} } for len(q) > 0 { e := q[0] q = q[1:] i, step := e.idx, e.step if i == len(arr)-1 { return step } step++ for _, j := range idx[arr[i]] { if !vis[j] { vis[j] = true q = append(q, pair{j, step}) } } delete(idx, arr[i]) if i+1 < len(arr) && !vis[i+1] { vis[i+1] = true q = append(q, pair{i + 1, step}) } if i-1 >= 0 && !vis[i-1] { vis[i-1] = true q = append(q, pair{i - 1, step}) } } return -1 }