Reach a Number - Problem
You are standing at position 0 on an infinite number line. There is a destination at position target.
You can make some number of moves numMoves so that:
- On each move, you can either go left or right.
- During the
ith move (starting fromi == 1toi == numMoves), you takeisteps in the chosen direction.
Given the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.
Input & Output
Example 1 — Basic Case
$
Input:
target = 3
›
Output:
2
💡 Note:
Move 1: go right 1 step (position = 1). Move 2: go right 2 steps (position = 3). Total: 2 moves to reach target 3.
Example 2 — Requires Backtracking
$
Input:
target = 2
›
Output:
3
💡 Note:
Move 1: go right 1 step (position = 1). Move 2: go right 2 steps (position = 3). Move 3: go left 3 steps (position = 0). But we can do better: Move 1: go right 1 step, Move 2: go left 2 steps (position = -1), Move 3: go right 3 steps (position = 2). Total: 3 moves.
Example 3 — Negative Target
$
Input:
target = -2
›
Output:
3
💡 Note:
Same as target = 2 due to symmetry. We can reach -2 by going left instead of right in the same number of moves.
Constraints
- -109 ≤ target ≤ 109
- target ≠ 0
Visualization
Tap to expand
Understanding the Visualization
1
Starting Position
Begin at position 0 on number line
2
Move Pattern
Each move i takes exactly i steps, choose left or right
3
Goal
Find minimum moves to reach target position
Key Takeaway
🎯 Key Insight: Use mathematical analysis of cumulative sums and parity to avoid exponential search
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code