#1654
Minimum Jumps to Reach Home
MediumArrayHash TableBreadth-First SearchHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a breadth-first search (BFS) strategy to explore all possible positions efficiently. By tracking the last jump direction, we ensure that the bug never jumps backward twice in a row, while also avoiding forbidden positions.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a queue for BFS starting from position 0 with 0 jumps.
- 2Step 2: Use a set to track visited positions to avoid cycles.
- 3Step 3: For each position, enqueue possible forward and backward jumps while respecting the jump rules.
solution.py18 lines
1# Full working Python code
2from collections import deque
3
4def minJumps(forbidden, a, b, x):
5 forbidden_set = set(forbidden)
6 queue = deque([(0, 0, 0)]) # (position, jumps, last_jump_direction)
7 visited = set()
8 while queue:
9 pos, jumps, last_jump = queue.popleft()
10 if pos == x:
11 return jumps
12 if pos < 0 or pos in forbidden_set or pos in visited:
13 continue
14 visited.add(pos)
15 queue.append((pos + a, jumps + 1, 1)) # Jump forward
16 if last_jump != -1: # Jump backward only if last jump was not backward
17 queue.append((pos - b, jumps + 1, -1)) # Jump backward
18 return -1ℹ
Complexity note: The complexity is linear because we explore each position at most once, and the queue operations are efficient.
- 1The bug can jump forward and backward, but cannot jump backward twice in a row, which adds complexity to the problem.
- 2Using a BFS approach ensures that we explore the shortest path to the target position efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.