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 a Number - Optimal Solution INPUT -2 -1 0 1 2 3 S Start T Target Input Values target = 3 start = 0 Move i: take i steps Direction: left or right Find minimum moves to reach target ALGORITHM STEPS 1 Sum Steps Add 1+2+3+... until sum >= |target| 2 Check Parity diff = sum - target must be even 3 Adjust if Odd If diff is odd, add more steps 4 Return Moves Count of steps taken Example: target = 3 Move 1: +1 --> pos = 1 Move 2: +2 --> pos = 3 sum = 1+2 = 3 = target diff = 0 (even) OK FINAL RESULT 0 1 2 3 +1 +2 S T OUTPUT 2 Minimum moves = 2 Move 1: 0 --> 1 (+1) Move 2: 1 --> 3 (+2) OK - Target Reached! Key Insight: Keep adding steps (1+2+3+...) until sum >= |target|. If (sum - target) is even, we can flip one step's direction to reduce sum by 2k (flipping step k changes sum by 2k). If diff is odd, continue adding steps until diff becomes even. Time complexity: O(sqrt(target)), Space: O(1). TutorialsPoint - Reach a Number | Optimal Solution (Mathematical Approach)
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