#754

Reach a Number

Medium
MathBinary SearchMathematical reasoningGreedy algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses mathematical reasoning to find the minimum number of moves required to reach the target. By calculating the sum of moves and using properties of arithmetic sequences, we can determine the minimum moves without simulating each path.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the absolute value of the target since the number line is symmetric.
  2. 2Step 2: Initialize a move counter and a sum variable to keep track of the total steps taken.
  3. 3Step 3: Increment the move counter and add the current move count to the sum until the sum is greater than or equal to the target and the difference between the sum and target is even.
solution.py15 lines
1# Full working Python code
2
3def reach_number(target):
4    target = abs(target)
5    move_count = 0
6    sum_moves = 0
7    while True:
8        move_count += 1
9        sum_moves += move_count
10        if sum_moves >= target and (sum_moves - target) % 2 == 0:
11            return move_count
12
13# Example usage
14print(reach_number(2))  # Output: 3
15print(reach_number(3))  # Output: 2

Complexity note: The time complexity is O(n) because we incrementally check each move until we find the minimum moves required to reach the target.

  • 1The target can be negative, but the approach remains the same by taking the absolute value.
  • 2The sum of the first n natural numbers is n(n+1)/2, which helps in determining the minimum moves.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.