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, iterate through arr
to identify each element along with its indices within arr
. Then, iterate over arr
once more to determine the subsequent indices for each index.
Adopt a dynamic programming approach. Begin from index 0 and, at each step, identify the next potential indices to which a jump can be made, updating the minimum number of jumps required for those indices. Continue this process until the last index is reached, then return the count of jumps required to arrive at the last index.
To optimize runtime, evaluate specific cases beforehand. If arr.length == 1
, it implies that the starting index is also the final index, thereby necessitating 0 jumps. If the element at the first index is identical to that at the last index, a direct jump to the last index suffices, warranting only 1 jump. Similarly, if the element at the first index matches the one at the penultimate index, two jumps are required: one to the penultimate index and another to the last index, totaling 2 jumps.
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} # visited 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))
-
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 }
-
function minJumps(arr: number[]): number { const g: Map<number, number[]> = new Map(); const n = arr.length; for (let i = 0; i < n; ++i) { if (!g.has(arr[i])) { g.set(arr[i], []); } g.get(arr[i])!.push(i); } let q: number[] = [0]; const vis: boolean[] = Array(n).fill(false); vis[0] = true; for (let ans = 0; ; ++ans) { const nq: number[] = []; for (const i of q) { if (i === n - 1) { return ans; } for (const j of g.get(arr[i])!) { if (!vis[j]) { vis[j] = true; nq.push(j); } } g.get(arr[i])!.length = 0; for (const j of [i - 1, i + 1]) { if (j >= 0 && j < n && !vis[j]) { vis[j] = true; nq.push(j); } } } q = nq; } }