VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-steps-to-reach-a-destination/

⇱ Minimum steps to reach a destination - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum steps to reach a destination

Last Updated : 2 May, 2026

Given an infinite number line. We start at 0 and can go either to the left or to the right. The condition is that in the ith move, you must take i steps. Given a destination d, the task is to find the minimum number of steps required to reach that destination.

Examples:

Input: d = 2
Output: 3
Explanation: The steps taken are +1, -2 and +3.

Input: d = 10
Output: 4
Explanation: The steps taken are +1, +2, +3 and +4.

[Naive Approach] Using Recursion - O( 2 ^ n) Time and O(d) Space

We can always reach any destination as it is always possible to make a move of length 1. At any step i, we can move forward i, then backward i + 1. Since the distance of +5 and -5 from 0 is the same, hence we find the answer for the absolute value of the destination. The idea is to recursively explore both left and right movements on a number line.

  • Starting from the origin (0), we recursively call for both movements with incremented number of steps and changed current position.
  • If the absolute value of the current position exceeds the destination, the path is considered invalid, and the function returns a large value.
  • If the current position matches the destination, the number of steps taken is returned.

Output
3

[Efficient Approach] Using Even/Odd Parity - O(n) Time and O(1) Space

We find the answer for the absolute value of the destination as steps would be the same. Starting from zero, we incrementally increase our steps, with each move allowing us to move a number of steps equal to the current move number. We continue moving forward, accumulating steps until we either reach or overshoot the target. The key complexity arises when we overshoot the target, which requires a adjustment of our moves:

Even Difference Scenario: When the total accumulated distance differs from the target by an even number, we can resolve this by flipping the sign of a specific move.
Example: Moves: 1 2 3 4 5 6 (total 21), target = 19

  • Difference is 2 (even)
  • We can flip 1 to -1, transforming the sequence to -1 2 3 4 5 6
  • This exactly reaches the target of 19

Odd Difference Scenario: When the difference is odd, we continue adding moves until we can create an even difference, which allows us to perform a strategic move-flipping adjustment.
Example: Moves 1 2 3 4 5 6 (total 21), target 20

  • Difference is 1 (odd)
  • We add another move (7), new total becomes 28
  • Difference is now 8 (even)
  • We can now flip 4th move to reach exactly 20, i.e., 1 2 3 -4 5 6 7

Output
3
Comment