Jump Game IV (LeetCode 1345): Solution and Explanation
Start at index 0 of an integer array. Each step moves to a neighbour (i - 1 or i + 1) or to any other index holding the same value. Return the fewest steps needed to reach the last index.
Intuition
Every move costs one step, so this is a shortest path problem in an unweighted graph whose nodes are array indices. Breadth-first search finds the answer: the level at which the last index is first popped is the minimum number of jumps.
The neighbour edges are easy. The same-value edges need a lookup, so build a map from each value to the list of indices that hold it. From index i, the teleport targets are exactly groups[arr[i]].
The catch is a long run of equal values. With 50,000 copies of 7, every one of them would scan the whole list of 50,000 indices, which is quadratic. But the first time any index with value 7 is popped, every other 7 gets enqueued at the very next level. Scanning that list again can never find anything new.
So delete the group right after its first use. Each index then enters the queue once and each group list is scanned once, and the whole search stays linear.
Approach: BFS with value groups removed after first use
- Build
groups, mapping each value to the list of indices with that value. - Start a BFS from index 0 with
seen[0] = Trueandsteps = 0. - Process the queue one level at a time. When the popped index is
n - 1, returnsteps. - Otherwise take
groups[arr[i]], remove it from the map, addi - 1andi + 1, and enqueue every in-range unseen index. - After each full level, increment
steps. The last index is always reachable by walking right, so the loop always returns.
Step-by-step example
arr = [100,-23,-23,404,100,23,23,23,3,404]
- Groups: 100 at [0, 4], -23 at [1, 2], 404 at [3, 9], 23 at [5, 6, 7].
- Level 0: pop 0. Teleport to 4 (also 100) and delete group 100. Step to neighbour 1. Queue: [4, 1].
- Level 1: pop 4, its group is gone, so only neighbours 3 and 5 are new. Pop 1, teleport to 2 and delete group -23. Queue: [3, 5, 2].
- Level 2: pop 3, teleport to 9 (also 404). Pop 5, teleport to 6 and 7, step nothing new. Pop 2, nothing new.
- Level 3: pop 9, which is the last index. Return 3. The route is 0 → 4 → 3 → 9.
Code: Python, Java, C++
1class Solution:
2 def minJumps(self, arr: List[int]) -> int:
3 n = len(arr)
4 groups = defaultdict(list)
5 for i, v in enumerate(arr):
6 groups[v].append(i)
7 seen = [False] * n
8 seen[0] = True
9 queue = deque([0])
10 steps = 0
11 while queue:
12 for _ in range(len(queue)):
13 i = queue.popleft()
14 if i == n - 1:
15 return steps
16 nexts = groups.pop(arr[i], [])
17 nexts += [i - 1, i + 1]
18 for j in nexts:
19 if 0 <= j < n and not seen[j]:
20 seen[j] = True
21 queue.append(j)
22 steps += 1
23 return -11class Solution {
2 public int minJumps(int[] arr) {
3 int n = arr.length;
4 Map<Integer, List<Integer>> groups = new HashMap<>();
5 for (int i = 0; i < n; i++) {
6 groups.computeIfAbsent(arr[i], key -> new ArrayList<>()).add(i);
7 }
8 boolean[] seen = new boolean[n];
9 seen[0] = true;
10 Deque<Integer> queue = new ArrayDeque<>();
11 queue.offer(0);
12 int steps = 0;
13 while (!queue.isEmpty()) {
14 for (int size = queue.size(); size > 0; size--) {
15 int i = queue.poll();
16 if (i == n - 1) {
17 return steps;
18 }
19 List<Integer> nexts = groups.getOrDefault(arr[i], new ArrayList<>());
20 groups.remove(arr[i]);
21 nexts.add(i - 1);
22 nexts.add(i + 1);
23 for (int j : nexts) {
24 if (j >= 0 && j < n && !seen[j]) {
25 seen[j] = true;
26 queue.offer(j);
27 }
28 }
29 }
30 steps++;
31 }
32 return -1;
33 }
34}1class Solution {
2public:
3 int minJumps(vector<int>& arr) {
4 int n = arr.size();
5 unordered_map<int, vector<int>> groups;
6 for (int i = 0; i < n; i++) {
7 groups[arr[i]].push_back(i);
8 }
9 vector<bool> seen(n, false);
10 seen[0] = true;
11 queue<int> q;
12 q.push(0);
13 int steps = 0;
14 while (!q.empty()) {
15 for (int size = q.size(); size > 0; size--) {
16 int i = q.front();
17 q.pop();
18 if (i == n - 1) {
19 return steps;
20 }
21 vector<int> nexts = move(groups[arr[i]]);
22 groups.erase(arr[i]);
23 nexts.push_back(i - 1);
24 nexts.push_back(i + 1);
25 for (int j : nexts) {
26 if (j >= 0 && j < n && !seen[j]) {
27 seen[j] = true;
28 q.push(j);
29 }
30 }
31 }
32 steps++;
33 }
34 return -1;
35 }
36};Time and space complexity
O(n)
Each index is enqueued at most once, and each value group is scanned exactly once before it is deleted, so total work is linear in the array length.
O(n)
The value map, the seen array and the queue each hold at most n entries.
Other approaches
BFS without deleting groups (time O(n^2), space O(n))
The same BFS, but leaving each group in the map. It is correct and fine for short arrays, but an array full of one repeated value makes every pop scan the whole group, which is O(n^2) and times out.
Bidirectional BFS (time O(n), space O(n))
Search from index 0 and from the last index at the same time and stop when the frontiers meet. It explores fewer nodes in practice but still needs the group deletion trick for the worst case.
Common mistakes
- Not deleting a value's index list after using it, which turns long runs of equal values into quadratic work.
- Deleting only the current index from the group instead of the whole group. Every other index in it was just enqueued, so the whole list is spent.
- Forgetting the single-element array, where the answer is 0 because you already stand on the last index.
- Marking indices as seen when popped instead of when pushed, which lets the same index enter the queue many times.
Frequently asked questions
Why is BFS the right search here?
Every jump has the same cost, one step. BFS explores indices in order of how many steps they need, so the first time it reaches the last index it has used the minimum number of steps.
Why is it safe to delete a value group after one use?
When the first index with value v is popped at level k, every other index with value v is enqueued at level k + 1. Any later index with value v is popped at level k + 1 or later, so teleporting from it can only reach indices that already have a level of k + 1 or less.
How does this differ from Jump Game III?
Jump Game III gives each index exactly two moves, i + arr[i] and i - arr[i]. Here each index can jump to its neighbours and to every same-value index, so the out-degree can be huge and needs the group deletion trick.
What is the time complexity?
O(n) time and O(n) space. Each index enters the queue once and each value group is scanned once.