algoadvance

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.

Clarifying Questions

  1. Negative Target: Can the target be negative?
    • Yes, you can treat the problem symmetrically because moving to a negative target is the same as moving to the positive one due to symmetry.
  2. Complexity Constraints: Is there any constraint on the value of the target?
    • The value of target is an integer and may be large, a brute-force approach may be infeasible.
  3. Starting Point: Do we always start from position 0?
    • Yes.

Strategy

The task is to minimize the number of steps required to reach the target position.

Steps to Approach:

  1. 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.

  2. 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.

  3. 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.

Code

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

Time Complexity

This approach efficiently calculates the minimum number of steps required to reach the target position on an infinite number line.

Try our interview co-pilot at AlgoAdvance.com