Skip to content
Problem 754 · LeetCode 754(opens in a new tab)

Reach a Number

MediumBinary search

You start at 0 on a number line that goes on forever in both directions. You make moves numbered 1, 2, 3 and so on: move i always covers exactly i units, but for each move you pick whether to go left or right.

Given a nonzero whole number target, return the smallest number of moves after which you can be standing exactly on target.

Example 1

Input:  target = 5
Output: 5
Why:    −1 + 2 + 3 − 4 + 5 = 5; four moves can only land on even spots
2 more examples and the constraints

Example 2

Input:  target = -4
Output: 3
Why:    −1 − 2 − 3 is −6; turning the first move around gives +1 − 2 − 3 = −4

Example 3

Input:  target = 6
Output: 3
Why:    1 + 2 + 3 = 6, every move to the right

Constraints

  • −1,000,000,000 ≤ target ≤ 1,000,000,000
  • target ≠ 0

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Add moves one at a timeO(√t)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for target = 1,000,000,000Verdict
Add moves one at a timeO(√t)
Simple; about 45,000 steps
Binary search the first kO(log t)
Best; about 30 steps

t = |target|.

Edge cases to test

  • Negative target. Mirror it: −4 needs the same 3 moves as 4.
  • target = ±1. One move of 1 unit; the answer is 1.
  • Sum lands exactly. target = 6 is 1 + 2 + 3: the overshoot is 0, which is even.
  • Two extra moves. target = 5: k = 3 overshoots by 1 and k = 4 by 5, so it takes k = 5.
  • Large target. target = 10⁹ needs 64-bit math for the sums in Java and C++.

Common mistakes

  • Stopping at the first k whose sum reaches t without checking that the overshoot is even.
  • Forgetting to take |target|, so a negative target loops forever or answers 0.
  • Computing mid * (mid + 1) in 32-bit integers.

How to talk through it

  1. 1Clarify. Can target be negative? Is it ever 0? Does move i always cover exactly i units?
  2. 2Use symmetry. Solve for |target|; mirroring every move handles the negative side.
  3. 3Find the parity rule. Flipping move j lowers the sum by 2j, so the overshoot must be even.
  4. 4Search, then fix parity. Binary search the first k that reaches t, then add at most two moves.
  5. 5Test out loud. Run 5, −4, 6 and 1 to check the zero, one and two extra-move cases.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?