Minimum Jumps to Reach Home - Problem
A bug starts at position 0 on the x-axis and wants to reach its home at position x.
The bug can move according to these rules:
- Jump exactly
apositions forward (to the right) - Jump exactly
bpositions backward (to the left) - Cannot jump backward twice in a row
- Cannot jump to any forbidden positions
- Cannot jump to negative positions
The bug may jump forward beyond its home, but it cannot go to negative positions.
Given an array forbidden where forbidden[i] means the bug cannot jump to position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home at position x. If impossible, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9
›
Output:
3
💡 Note:
Bug jumps: 0 → 3 → 6 → 9. Three forward jumps of size 3 each reach position 9.
Example 2 — Impossible Case
$
Input:
forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11
›
Output:
-1
💡 Note:
Position 11 cannot be reached due to forbidden positions and jump constraints.
Example 3 — Single Jump
$
Input:
forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7
›
Output:
2
💡 Note:
Bug can jump: 0 → 16 → 7 (forward jump to 16, then backward jump to 7).
Constraints
- 1 ≤ forbidden.length ≤ 1000
- 1 ≤ a, b, forbidden[i] ≤ 2000
- 0 ≤ x ≤ 2000
- All values in forbidden are distinct
- Position x is not forbidden
Visualization
Tap to expand
Understanding the Visualization
1
Input
forbidden=[14,4,18,1,15], a=3, b=15, x=9
2
Process
Find shortest path using BFS with state tracking
3
Output
Minimum 3 jumps: 0→3→6→9
Key Takeaway
🎯 Key Insight: Use BFS with state tracking to handle the consecutive backward jump constraint efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code