Problem Description
We start at position 0 on an infinite number line and want to reach a target position using a series of moves. On the iᵗʰ move, we can take exactly i steps either to the right or left. Our goal is to determine the minimum number of moves required to reach the given target.
Key Insights
- Due to symmetry, work with the absolute value of the target.
- The sum of the first n natural numbers is n(n+1)/2. We need this sum to be at least the absolute target.
- Flipping a move changes the total by an even number. Therefore, the difference between the sum and the target must be even.
- Iterate n until both conditions are met: total distance is large enough and the difference (total - target) is even.
Space and Time Complexity
Time Complexity: O(n), where n is the minimum number of moves needed (typically much smaller than target). Space Complexity: O(1).
Solution
The approach first converts the target to its absolute value. We then search for the smallest integer n such that the sum of the first n natural numbers (S = n(n+1)/2) is at least the target and (S - target) is even. This even difference indicates that we can flip the signs of certain moves to exactly hit the target. The solution uses a simple iterative method to find such n.