Minimum steps to reach a destination

28 Jun, 2022
Given a number line from -infinity to +infinity. You start at 0 and can go either to the left or to the right. The condition is that in i’th move, you take i steps. 
Find if you can reach a given number x Find the most optimal way to reach a given number x, if we can indeed reach it. For example, 3 can be reached in 2 steps, (0, 1) (1, 3) and 4 can be reached in 3 steps (0, -1), (-1, 1) (1, 4).
Find if you can reach a given number x 
Find the most optimal way to reach a given number x, if we can indeed reach it. For example, 3 can be reached in 2 steps, (0, 1) (1, 3) and 4 can be reached in 3 steps (0, -1), (-1, 1) (1, 4).
Source: Flipkart Interview Question
The important thing to note is we can 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.Below is a recursive solution suggested by Arpit Thapar here. 
Since distance of + 5 and – 5 from 0 is same, hence we find answer for absolute value of destination.We use a recursive function which takes as arguments: Source Vertex Value of last step taken Destination If at any point source vertex = destination; return number of steps.Otherwise we can go in both of the possible directions. Take the minimum of steps in both cases.From any vertex we can go to : (current source + last step +1) and (current source – last step -1)If at any point, absolute value of our position exceeds the absolute value of our destination then it is intuitive that the shortest path is not possible from here. Hence we make the value of steps INT_MAX, so that when i take the minimum of both possibilities, this one gets eliminated. 
Since distance of + 5 and – 5 from 0 is same, hence we find answer for absolute value of destination.
We use a recursive function which takes as arguments: Source Vertex Value of last step taken Destination
Source Vertex Value of last step taken Destination
Source Vertex 
Value of last step taken 
Destination
 If at any point source vertex = destination; return number of steps.
Otherwise we can go in both of the possible directions. Take the minimum of steps in both cases.From any vertex we can go to : (current source + last step +1) and (current source – last step -1)
From any vertex we can go to : (current source + last step +1) and (current source – last step -1)
(current source + last step +1) and 
(current source – last step -1)
If at any point, absolute value of our position exceeds the absolute value of our destination then it is intuitive that the shortest path is not possible from here. Hence we make the value of steps INT_MAX, so that when i take the minimum of both possibilities, this one gets eliminated. 
If we don’t use this last step, the program enters into an INFINITE recursion and gives RUN TIME ERROR.
Below is the implementation of above idea. Note that the solution only counts steps. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count number of// steps to reach a point#include<bits/stdc++.h>using namespace std; // Function to count number of steps// required to reach a destination // source -> source vertex// step -> value of last step taken// dest -> destination vertexint steps(int source, int step, int dest){    // base cases    if (abs(source) > (dest))         return INT_MAX;    if (source == dest) return step;     // at each point we can go either way     // if we go on positive side    int pos = steps(source + step + 1,                      step + 1, dest);     // if we go on negative side    int neg = steps(source - step - 1,                      step + 1, dest);     // minimum of both cases    return min(pos, neg);} // Driver codeint main(){    int dest = 11;    cout << "No. of steps required to reach "                            << dest << " is "                        << steps(0, 0, dest);    return 0;}
// Java program to count number of// steps to reach a pointimport java.io.*; class GFG{     // Function to count number of steps    // required to reach a destination         // source -> source vertex    // step -> value of last step taken    // dest -> destination vertex    static int steps(int source, int step,                                int dest)    {        // base cases        if (Math.abs(source) > (dest))            return Integer.MAX_VALUE;             if (source == dest)            return step;         // at each point we can go either way         // if we go on positive side        int pos = steps(source + step + 1,                        step + 1, dest);         // if we go on negative side        int neg = steps(source - step - 1,                        step + 1, dest);         // minimum of both cases        return Math.min(pos, neg);    }     // Driver Code    public static void main(String[] args)    {        int dest = 11;        System.out.println("No. of steps required"+                                " to reach " + dest +                       " is " + steps(0, 0, dest));    }} // This code is contributed by Prerna Saini
# python program to count number of# steps to reach a pointimport sys # Function to count number of steps# required to reach a destination     # source -> source vertex# step -> value of last step taken# dest -> destination vertexdef steps(source, step, dest):         #base cases    if (abs(source) > (dest)) :        return sys.maxsize         if (source == dest):        return step     # at each point we can go    # either way     # if we go on positive side    pos = steps(source + step + 1,                    step + 1, dest)     # if we go on negative side    neg = steps(source - step - 1,                    step + 1, dest)     # minimum of both cases    return min(pos, neg)      # Driver Codedest = 11;print("No. of steps required",               " to reach " ,dest ,        " is " , steps(0, 0, dest));      # This code is contributed by Sam007.
// C# program to count number of// steps to reach a pointusing System; class GFG{    // Function to count number of steps    // required to reach a destination         // source -> source vertex    // step -> value of last step taken    // dest -> destination vertex    static int steps(int source, int step,                                int dest)    {        // base cases        if (Math.Abs(source) > (dest))            return int.MaxValue;             if (source == dest)                return step;         // at each point we can go either way         // if we go on positive side        int pos = steps(source + step + 1,                        step + 1, dest);         // if we go on negative side        int neg = steps(source - step - 1,                        step + 1, dest);         // minimum of both cases        return Math.Min(pos, neg);    }     // Driver Code    public static void Main()    {        int dest = 11;        Console.WriteLine("No. of steps required"+                             " to reach " + dest +                      " is " + steps(0, 0, dest));    }} // This code is contributed by Sam007
<?php// PHP program to count number// of steps to reach a point // Function to count number// of steps required to reach// a destination // source -> source vertex// step -> value of last step taken// dest -> destination vertexfunction steps($source, $step, $dest){    // base cases    if (abs($source) > ($dest))        return PHP_INT_MAX;    if ($source == $dest)        return $step;     // at each point we    // can go either way     // if we go on positive side    $pos = steps($source + $step + 1,                   $step + 1, $dest);     // if we go on negative side    $neg = steps($source - $step - 1,                   $step + 1, $dest);     // minimum of both cases    return min($pos, $neg);} // Driver code$dest = 11;echo "No. of steps required to reach ",     $dest, " is ", steps(0, 0, $dest); // This code is contributed by aj_36?>
<script>// JavaScript program to count number of// steps to reach a point // Function to count number of steps// required to reach a destination // source -> source vertex// step -> value of last step taken// dest -> destination vertexfunction steps(source, step, dest){     // base cases    if (Math.abs(source) > (dest))        return Number.MAX_SAFE_INTEGER;    if (source == dest) return step;     // at each point we can go either way    // if we go on positive side    let pos = steps(source + step + 1,                    step + 1, dest);     // if we go on negative side    let neg = steps(source - step - 1,                    step + 1, dest);     // minimum of both cases    return Math.min(pos, neg);} // Driver code    let dest = 11;    document.write("No. of steps required to reach "                            + dest + " is "                        + steps(0, 0, dest)); // This code is contributed by Surbhi Tyagi.</script>
No. of steps required to reach 11 is 5
Thanks to Arpit Thapar for providing above algorithm and implementation. 
Optimized Solution : Find minimum moves to reach target on an infinite line
This article is contributed by Abhay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
jit_t
yvvijay
surbhityagi15
hardikkoriintern
Amazon
BFS
DFS
Flipkart
Goldman Sachs
InMobi
Microsoft
Dynamic Programming
Graph
Recursion
Flipkart
Amazon
Microsoft
Goldman Sachs
InMobi
Dynamic Programming
Recursion
DFS
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.