{x}
blog image

Reach a Number

You are standing at position 0 on an infinite number line. There is a destination at position target.

You can make some number of moves numMoves so that:

  • On each move, you can either go left or right.
  • During the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction.

Given the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.

 

Example 1:

Input: target = 2
Output: 3
Explanation:
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).

Example 2:

Input: target = 3
Output: 2
Explanation:
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).

 

Constraints:

  • -109 <= target <= 109
  • target != 0

Solution Explanation for LeetCode 754: Reach a Number

This problem asks for the minimum number of moves to reach a target position on an infinite number line, where each move is an incrementing number of steps. The key insight is leveraging the symmetry of the problem: we can move left or right.

Approach: Mathematical Analysis

The solution utilizes a mathematical approach to find the minimum number of moves. Instead of simulating the moves, it directly calculates the minimum required moves based on the properties of the sum of consecutive integers.

  1. Absolute Value: We take the absolute value of the target. This is because the number of moves to reach target is the same as the number of moves to reach -target due to the symmetry of moving left or right.

  2. Sum of Consecutive Integers: The sum of the first k integers is given by the formula k*(k+1)/2. This represents the total distance we can cover in k moves.

  3. Iteration: We iterate, incrementing k (the number of moves) and calculating the sum s until two conditions are met:

    • s >= target: We've covered at least the distance to the target.
    • (s - target) % 2 == 0: The difference between the covered distance (s) and the target is an even number. This condition ensures that we can adjust some of our moves (by changing their direction from positive to negative or vice versa) to precisely land on the target. An even difference implies we can achieve this adjustment.

Time and Space Complexity

  • Time Complexity: O(√|target|). The loop iterates approximately until k*(k+1)/2 is close to target, which means k grows roughly as the square root of target.

  • Space Complexity: O(1). The solution uses only a few variables to store the intermediate calculations; it doesn't use any data structures that scale with the input size.

Code Implementation (Python3)

class Solution:
    def reachNumber(self, target: int) -> int:
        target = abs(target)
        s = k = 0
        while 1:
            if s >= target and (s - target) % 2 == 0:
                return k
            k += 1
            s += k

This code directly implements the mathematical approach described above. The while 1: loop continues until the conditions for a valid solution are met. The k variable is then returned as the minimum number of moves.

Code Implementations in Other Languages

The same mathematical logic can be implemented in other languages; the code structure will be very similar. Here are examples in Java, C++, Go, and Javascript:

Java

class Solution {
    public int reachNumber(int target) {
        target = Math.abs(target);
        int s = 0, k = 0;
        while (true) {
            if (s >= target && (s - target) % 2 == 0) {
                return k;
            }
            ++k;
            s += k;
        }
    }
}

C++

class Solution {
public:
    int reachNumber(int target) {
        target = abs(target);
        int s = 0, k = 0;
        while (1) {
            if (s >= target && (s - target) % 2 == 0) return k;
            ++k;
            s += k;
        }
    }
};

Go

func reachNumber(target int) int {
	target = abs(target)
	s, k := 0, 0
	for {
		if s >= target && (s-target)%2 == 0 {
			return k
		}
		k++
		s += k
	}
}
 
func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

JavaScript

/**
 * @param {number} target
 * @return {number}
 */
var reachNumber = function(target) {
    target = Math.abs(target);
    let s = 0, k = 0;
    while (true) {
        if (s >= target && (s - target) % 2 == 0) {
            return k;
        }
        k++;
        s += k;
    }
};

These implementations are functionally equivalent to the Python version, demonstrating the adaptability of the mathematical solution across programming languages.