Reach a Number - Problem
Imagine you're standing at position 0 on an infinite number line, and you need to reach a specific target position. Here's the twist: on your i-th move, you must take exactly i steps, but you can choose to go either left or right.

For example, on move 1 you take 1 step, on move 2 you take 2 steps, on move 3 you take 3 steps, and so on. Your goal is to find the minimum number of moves required to reach the target position.

Example: To reach target = 3, you could go right 1 step (position 1), then right 2 steps (position 3). That's 2 moves total.

Input & Output

example_1.py — Basic Case
$ Input: target = 2
Output: 3
💡 Note: On the 1st move we step from 0 to 1. On the 2nd move we step from 1 to -1. On the 3rd move we step from -1 to 2. So we need 3 moves total: Right 1, Left 2, Right 3 → positions: 1, -1, 2
example_2.py — Perfect Match
$ Input: target = 3
Output: 2
💡 Note: On the 1st move we step from 0 to 1. On the 2nd move we step from 1 to 3. Total sum 1+2=3 equals target, so we reach it in 2 moves: Right 1, Right 2 → positions: 1, 3
example_3.py — Negative Target
$ Input: target = -2
Output: 3
💡 Note: Due to symmetry, reaching -2 requires the same number of moves as reaching +2. We can go Left 1, Right 2, Left 3 → positions: -1, 1, -2

Constraints

  • -109 ≤ target ≤ 109
  • target ≠ 0
  • Time limit: 1 second per test case

Visualization

Tap to expand
The Magic Staircase JourneyStep 1Step 2Step 3Step 4🎯 Target might be here+1 step+2 steps+3 steps!Overshot by even amount?Flip one step direction!✨ Magic Formula:1. Keep adding steps: 1+2+3+... until sum ≥ target2. If sum = target → Done!3. If (sum - target) is even → Flip one step, Done!4. If (sum - target) is odd → Add 1-2 more steps until even
Understanding the Visualization
1
Keep going right
Move right with increasing step sizes until you reach or pass the target
2
Check overshoot
If you overshot by an even amount, you can flip one previous move
3
Adjust if needed
If overshoot is odd, take 1-2 more steps until it becomes even
Key Takeaway
🎯 Key Insight: Mathematics beats brute force! Instead of trying all 2^n paths, we use the fact that overshooting by an even amount always allows a perfect adjustment.
Asked in
Google 42 Microsoft 35 Amazon 28 Meta 22
58.4K Views
Medium Frequency
~25 min Avg. Time
1.9K 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