Ctrl K

Grasshopper Going Home

Medium
A grasshopper sits at point 0 on the number line, and its home is at point home. It hops by these rules: - a forward hop moves exactly forward to the right; - a back hop moves exactly back to the left; - it never makes two back hops in a row; - it may never land on a negative point or on any point listed in traps. Overshooting is allowed: the grasshopper may go past home and come back later. Return the fewest hops that land the grasshopper exactly on home, or -1 if that is impossible.
Example 1
traps=[2, 9], forward=4, back=3, home=5 → 3

For example 0 → 4 → 1 → 5: forward, back, forward. Position 5 cannot be reached in fewer than three hops.

Example 2
traps=[4], forward=4, back=1, home=3 → -1

The forward hop lands on the trap at 4 and a backward hop from 0 would go negative, so the grasshopper cannot move.

Example 3
traps=[1], forward=2, back=1, home=0 → 0

The grasshopper is already home.

Constraints
  • 0 ≤ len(traps) ≤ 1000
  • 1 ≤ traps[i] ≤ 2000, all values in traps are distinct
  • 1 ≤ forward, back ≤ 2000
  • 0 ≤ home ≤ 2000
  • home is not in traps
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Bills MediumSteps to the Nearest Zero MediumFarthest From Any Shore MediumBlock the Only Route MediumStones on a 3 × 3 Board Medium
loading Python…
Input
traps=[2, 9], forward=4, back=3, home=5
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 89 tests on the server, hidden ones included.