#1345

Jump Game IV

Hard
ArrayHash TableBreadth-First SearchHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses Breadth-First Search (BFS) to explore the shortest path to the last index. By leveraging a graph representation of the indices and their connections based on values, we can efficiently find the minimum steps.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a graph where each value in the array points to all indices that have the same value.
  2. 2Step 2: Use BFS starting from index 0, keeping track of visited indices to avoid cycles.
  3. 3Step 3: For each index, explore the next index (i + 1), previous index (i - 1), and all indices with the same value as arr[i].
  4. 4Step 4: Return the number of steps when reaching the last index.
solution.py27 lines
1# Full working Python code
2from collections import defaultdict, deque
3
4def minJumps(arr):
5    n = len(arr)
6    if n <= 1:
7        return 0
8    visited = set()
9    graph = defaultdict(list)
10    for i in range(n):
11        graph[arr[i]].append(i)
12
13    queue = deque([(0, 0)])  # (index, steps)
14    visited.add(0)
15
16    while queue:
17        index, steps = queue.popleft()
18        if index == n - 1:
19            return steps
20        # Check next and previous indices
21        for next_index in [index + 1, index - 1] + graph[arr[index]]:
22            if 0 <= next_index < n and next_index not in visited:
23                visited.add(next_index)
24                queue.append((next_index, steps + 1))
25        graph[arr[index]].clear()  # Clear to prevent future jumps
26
27    return -1

Complexity note: The time complexity is O(n) because each index is processed once, and the space complexity is O(n) due to the storage of the graph and visited set.

  • 1Using BFS ensures that we find the shortest path to the last index efficiently.
  • 2Clearing the graph after processing an index prevents unnecessary future jumps.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.