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 from i == 1 to i == numMoves), you take i steps 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
Reach Target = 3 with Minimum Moves0Start123Target4Move 1: +1Move 2: +2Solution Path:Position 0 → +1 → Position 1Position 1 → +2 → Position 3Minimum moves required: 2Each move i allows exactly i steps in chosen direction
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
Asked in
Google 25 Microsoft 18 Amazon 12
28.0K Views
Medium Frequency
~25 min Avg. Time
850 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