LeetCode 754: Reach a Number Solution

Master LeetCode problem 754 (Reach a Number), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

754. Reach a Number

Problem Explanation

Explanation

To solve this problem, we can simulate the process of reaching the target by making moves left or right. The key insight is that the sum of the first n positive integers is (n * (n + 1)) / 2. We can adjust the target to make use of this formula and then find the minimum number of moves required to reach that adjusted target.

  1. Adjust the target:

    • Take the absolute value of the target to avoid confusion with direction.
    • Initialize a variable sum to store the sum of 1 to some n.
    • Increment n until sum is greater than or equal to the absolute target value.
    • Calculate the difference diff = sum - target.
  2. Handle the parity of the difference:

    • If diff is even, we can reach the target by flipping the sign of some number. This is because moving back and forth the same distance cancels out the difference.
    • If diff is odd, we need to keep adding n+1 to sum until the difference becomes even.
  3. Calculate the minimum number of moves:

    • If the difference is even, the number of moves required is n.
    • If the difference is odd, we need to add n+1 to make the difference even, which requires at least one more move.

Solution Code

class Solution {
    public int reachNumber(int target) {
        target = Math.abs(target);
        int n = 1;
        int sum = 0;
        while (sum < target || (sum - target) % 2 != 0) {
            sum += n;
            n++;
        }
        return n - 1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 754 (Reach a Number)?

This page provides optimized solutions for LeetCode problem 754 (Reach a Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 754 (Reach a Number)?

The time complexity for LeetCode 754 (Reach a Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 754 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 754 in Java, C++, or Python.

Back to LeetCode Solutions