The problem “Reach a Number” on LeetCode is stated as follows:
You are standing at position 0 on an infinite number line. There is a destination at position target
.
You can make a move of +1, -1, +2, -2, +3, -3, …, etc.
In other words, on the i-th
move, you can choose to move either i
steps to the right or i
steps to the left.
Return the minimum number of moves required to reach the target
.
target
is an integer and may be large, a brute-force approach may be infeasible.The task is to minimize the number of steps required to reach the target position.
Steps to Approach:
Symmetry: Since the problem is symmetric around 0, we can always consider target
as positive. If the target
is negative, we can take its absolute value.
Sum of First N Naturals: We consider making steps of 1, 2, 3, ..., k
by summing these steps. This series sum is S = k * (k + 1) / 2
.
Find Minimum k: Find the smallest k
such that S
is greater than or equal to the target. However, S
should be adjusted to ensure that the difference between S
and target
is an even number, because only then can the positive and negative step adjustments ultimately balance out to reach the exact target.
class Solution:
def reachNumber(self, target: int) -> int:
target = abs(target) # Treat as positive for symmetry
step = 0
sum_steps = 0
# Keep incrementing the step until the cumulative sum is at least the target,
# and the difference between sum_steps and target is even.
while sum_steps < target or (sum_steps - target) % 2 != 0:
step += 1
sum_steps += step
return step
# Example usage:
sol = Solution()
print(sol.reachNumber(3)) # Output: 2
print(sol.reachNumber(2)) # Output: 3
This approach efficiently calculates the minimum number of steps required to reach the target position on an infinite number line.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?