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 a positions forward (to the right)
  • Jump exactly b positions 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
Minimum Jumps to Reach Home - BFS INPUT 0 4 9 14 15 18 Bug Home X = Forbidden forbidden = [14, 4, 18, 1, 15] a = 3 b = 15 x = 9 (target) Rules: - Jump forward: +a positions - Jump backward: -b positions - No 2 backward jumps in a row - No forbidden/negative positions ALGORITHM STEPS 1 Initialize BFS Queue: [(0, 0, false)] (pos, jumps, wasBack) 2 Process pos=0 Forward: 0+3=3 [OK] Queue: [(3, 1, false)] 3 Process pos=3 Forward: 3+3=6 [OK] Back: 3-15 negative [X] 4 Process pos=6 Forward: 6+3=9 [OK] Target reached! BFS Path: 0 +3 3 +3 6 +3 9 Level 0 --} Level 1 --} Level 2 --} Level 3 FINAL RESULT Minimum Jumps Found! 3 jumps Optimal Path: Jump 1: 0 --} 3 (+3) Jump 2: 3 --} 6 (+3) Jump 3: 6 --} 9 (+3) [OK] Home Reached! Output: 3 All forward jumps No forbidden hit Key Insight: BFS guarantees minimum jumps because it explores all positions at distance k before distance k+1. State includes direction of last jump to handle "no consecutive backward jumps" constraint. Upper bound for search: max(x, max(forbidden)) + a + b to ensure we don't miss valid paths. TutorialsPoint - Minimum Jumps to Reach Home | BFS Approach
Asked in
Google 15 Facebook 12 Amazon 8
23.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen