Reach a Number — LeetCode 754 Python Solution

MediumMathBinary Search
Problem
#754
Reading time
2 min

The problem

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

Example

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

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(\sqrt{\left | \textit{target} \right | })
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 754. Reach a Number is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 754. Reach a Number?
LeetCode 754. Reach a Number is rated Medium on LeetCode.
What is the time complexity of LeetCode 754. Reach a Number?
The Python solution on this page runs in O(\sqrt{\left | \textit{target} \right | }).
What is the space complexity of LeetCode 754. Reach a Number?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 754. Reach a Number cover?
LeetCode 754. Reach a Number is tagged Math and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview