Open In App

Check if it is possible to reach a number by making jumps of two given length

Last Updated : 16 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a starting position ‘k’ and two jump sizes ‘d1’ and ‘d2’, our task is to find the minimum number of jumps needed to reach ‘x’ if it is possible.
At any position P, we are allowed to jump to positions : 

  • P + d1 and P – d1
  • P + d2 and P – d2

Examples: 

Input : k = 10, d1 = 4, d2 = 6 and x = 8 
Output : 2
1st step 10 + d1 = 14
2nd step 14 - d2 = 8

Input : k = 10, d1 = 4, d2 = 6 and x = 9
Output : -1
-1 indicates it is not possible to reach x.

In the previous article we discussed a strategy to check whether a list of numbers is reachable by K by making jump of two given lengths. 

Here, instead of a list of numbers, we are given a single integer x and if it is reachable from k then the task is to find the minimum number of steps or jumps needed. 

We will solve this using Breadth first Search

Approach

  • Check if ‘x’ is reachable from k. The number x is reachable from k if it satisfies (x – k) % gcd(d1, d2) = 0.
  • If x is reachable : 
    1. Maintain a hash table to store the already visited positions.
    2. Apply bfs algorithm starting from position k.
    3. If you reach position P in ‘stp’ steps, you can reach p+d1 position in ‘stp+1’ steps.
    4. If position P is the required position ‘x’ then steps taken to reach P is the answer

The image below depicts how the algorithm finds out number of steps needed to reach x = 8 with k = 10, d1 = 4 and d2 = 6. 

Below is the implementation of the above approach: 

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to perform BFS traversal to
// find minimum number of step needed
// to reach x from K
int minStepsNeeded(int k, int d1, int d2, int x)
{
    // Calculate GCD of d1 and d2
    int gcd = __gcd(d1, d2);
 
    // If position is not reachable
    // return -1
    if ((k - x) % gcd != 0)
        return -1;
 
    // Queue for BFS
    queue<pair<int, int> > q;
 
    // Hash Table for marking
    // visited positions
    unordered_set<int> visited;
 
    // we need 0 steps to reach K
    q.push({ k, 0 });
 
    // Mark starting position
    // as visited
    visited.insert(k);
 
    while (!q.empty()) {
 
        int s = q.front().first;
 
        // stp is the number of steps
        // to reach position s
        int stp = q.front().second;
 
        if (s == x)
            return stp;
 
        q.pop();
 
        if (visited.find(s + d1) == visited.end()) {
 
            // if position not visited
            // add to queue and mark visited
            q.push({ s + d1, stp + 1 });
 
            visited.insert(s + d1);
        }
 
        if (visited.find(s + d2) == visited.end()) {
            q.push({ s + d2, stp + 1 });
            visited.insert(s + d2);
        }
 
        if (visited.find(s - d1) == visited.end()) {
            q.push({ s - d1, stp + 1 });
            visited.insert(s - d1);
        }
        if (visited.find(s - d2) == visited.end()) {
            q.push({ s - d2, stp + 1 });
            visited.insert(s - d2);
        }
    }
}
 
// Driver Code
int main()
{
    int k = 10, d1 = 4, d2 = 6, x = 8;
 
    cout << minStepsNeeded(k, d1, d2, x);
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
static class pair
{
    int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
static int __gcd(int a, int b)
{
    if (b == 0)
        return a;
    return __gcd(b, a % b);
     
}
// Function to perform BFS traversal to
// find minimum number of step needed
// to reach x from K
static int minStepsNeeded(int k, int d1,
                          int d2, int x)
{
    // Calculate GCD of d1 and d2
    int gcd = __gcd(d1, d2);
 
    // If position is not reachable
    // return -1
    if ((k - x) % gcd != 0)
        return -1;
 
    // Queue for BFS
    Queue<pair> q = new LinkedList<>();
 
    // Hash Table for marking
    // visited positions
    HashSet<Integer> visited = new HashSet<>();
 
    // we need 0 steps to reach K
    q.add(new pair(k, 0 ));
 
    // Mark starting position
    // as visited
    visited.add(k);
 
    while (!q.isEmpty())
    {
        int s = q.peek().first;
 
        // stp is the number of steps
        // to reach position s
        int stp = q.peek().second;
 
        if (s == x)
            return stp;
 
        q.remove();
 
        if (!visited.contains(s + d1))
        {
 
            // if position not visited
            // add to queue and mark visited
            q.add(new pair(s + d1, stp + 1));
 
            visited.add(s + d1);
        }
 
        if (visited.contains(s + d2))
        {
            q.add(new pair(s + d2, stp + 1));
            visited.add(s + d2);
        }
 
        if (!visited.contains(s - d1))
        {
            q.add(new pair(s - d1, stp + 1));
            visited.add(s - d1);
        }
        if (!visited.contains(s - d2))
        {
            q.add(new pair(s - d2, stp + 1));
            visited.add(s - d2);
        }
    }
    return Integer.MIN_VALUE;
}
 
// Driver Code
public static void main(String[] args)
{
    int k = 10, d1 = 4, d2 = 6, x = 8;
 
    System.out.println(minStepsNeeded(k, d1, d2, x));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 implementation of the approach
from math import gcd as __gcd
from collections import deque as queue
 
# Function to perform BFS traversal to
# find minimum number of step needed
# to reach x from K
def minStepsNeeded(k, d1, d2, x):
     
    # Calculate GCD of d1 and d2
    gcd = __gcd(d1, d2)
 
    # If position is not reachable
    # return -1
    if ((k - x) % gcd != 0):
        return -1
 
    # Queue for BFS
    q = queue()
 
    # Hash Table for marking
    # visited positions
    visited = dict()
 
    # we need 0 steps to reach K
    q.appendleft([k, 0])
 
    # Mark starting position
    # as visited
    visited[k] = 1
 
    while (len(q) > 0):
 
        sr = q.pop()
        s, stp = sr[0], sr[1]
 
        # stp is the number of steps
        # to reach position s
        if (s == x):
            return stp
 
        if (s + d1 not in visited):
 
            # if position not visited
            # add to queue and mark visited
            q.appendleft([(s + d1), stp + 1])
 
            visited[(s + d1)] = 1
 
        if (s + d2 not in visited):
            q.appendleft([(s + d2), stp + 1])
            visited[(s + d2)] = 1
 
        if (s - d1 not in visited):
            q.appendleft([(s - d1), stp + 1])
            visited[(s - d1)] = 1
 
        if (s - d2 not in visited):
            q.appendleft([(s - d2), stp + 1])
            visited[(s - d2)] = 1
 
# Driver Code
k = 10
d1 = 4
d2 = 6
x = 8
 
print(minStepsNeeded(k, d1, d2, x))
 
# This code is contributed by Mohit Kumar


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;            
     
class GFG
{
public class pair
{
    public int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
static int __gcd(int a, int b)
{
    if (b == 0)
        return a;
    return __gcd(b, a % b);
     
}
 
// Function to perform BFS traversal to
// find minimum number of step needed
// to reach x from K
static int minStepsNeeded(int k, int d1,
                          int d2, int x)
{
    // Calculate GCD of d1 and d2
    int gcd = __gcd(d1, d2);
 
    // If position is not reachable
    // return -1
    if ((k - x) % gcd != 0)
        return -1;
 
    // Queue for BFS
    Queue<pair> q = new Queue<pair>();
 
    // Hash Table for marking
    // visited positions
    HashSet<int> visited = new HashSet<int>();
 
    // we need 0 steps to reach K
    q.Enqueue(new pair(k, 0));
 
    // Mark starting position
    // as visited
    visited.Add(k);
 
    while (q.Count != 0)
    {
        int s = q.Peek().first;
 
        // stp is the number of steps
        // to reach position s
        int stp = q.Peek().second;
 
        if (s == x)
            return stp;
 
        q.Dequeue();
 
        if (!visited.Contains(s + d1))
        {
 
            // if position not visited
            // add to queue and mark visited
            q.Enqueue(new pair(s + d1, stp + 1));
 
            visited.Add(s + d1);
        }
 
        if (!visited.Contains(s + d2))
        {
            q.Enqueue(new pair(s + d2, stp + 1));
            visited.Add(s + d2);
        }
 
        if (!visited.Contains(s - d1))
        {
            q.Enqueue(new pair(s - d1, stp + 1));
            visited.Add(s - d1);
        }
        if (!visited.Contains(s - d2))
        {
            q.Enqueue(new pair(s - d2, stp + 1));
            visited.Add(s - d2);
        }
    }
    return int.MinValue;
}
 
// Driver Code
public static void Main(String[] args)
{
    int k = 10, d1 = 4, d2 = 6, x = 8;
 
    Console.WriteLine(minStepsNeeded(k, d1, d2, x));
}
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// JavaScript implementation of the approach
 
function __gcd(a,b)
{
    if (b == 0)
        return a;
    return __gcd(b, a % b);
}
 
// Function to perform BFS traversal to
// find minimum number of step needed
// to reach x from K
function minStepsNeeded(k,d1,d2,x)
{
    // Calculate GCD of d1 and d2
    let gcd = __gcd(d1, d2);
   
    // If position is not reachable
    // return -1
    if ((k - x) % gcd != 0)
        return -1;
   
    // Queue for BFS
    let q = [];
   
    // Hash Table for marking
    // visited positions
    let visited = new Set();
   
    // we need 0 steps to reach K
    q.push([k, 0 ]);
   
    // Mark starting position
    // as visited
    visited.add(k);
   
    while (q.length!=0)
    {
        let s = q[0][0];
   
        // stp is the number of steps
        // to reach position s
        let stp = q[0][1];
   
        if (s == x)
            return stp;
   
        q.shift();
   
        if (!visited.has(s + d1))
        {
   
            // if position not visited
            // add to queue and mark visited
            q.push([s + d1, stp + 1]);
   
            visited.add(s + d1);
        }
   
        if (!visited.has(s + d2))
        {
            q.push([s + d2, stp + 1]);
            visited.add(s + d2);
        }
   
        if (!visited.has(s - d1))
        {
            q.push([s - d1, stp + 1]);
            visited.add(s - d1);
        }
        if (!visited.has(s - d2))
        {
            q.push([s - d2, stp + 1]);
            visited.add(s - d2);
        }
    }
    return Number.MIN_VALUE;
}
 
// Driver Code
let k = 10, d1 = 4, d2 = 6, x = 8;
document.write(minStepsNeeded(k, d1, d2, x));
 
 
// This code is contributed by patel2127
 
</script>


Output

2

Complexity Analysis:

  • Time Complexity:  O(|k-x|) 
  • Auxiliary Space: O(|k-x|)


Similar Reads

Reach the numbers by making jumps of two given lengths
Given integers k, d1, d2 and an integer array arr[]. Starting from number k you are allowed to make jumps of size d1 and d2 i.e. all the possible moves from k are: k + d1 and k - d1k + d2 and k - d2 The task is to find which of the numbers from the array are reachable from k making any number of jumps and any given jump is either of size d1 or d2.
8 min read
Maximum jumps to reach end of Array with condition that index i can make arr[i] jumps
Given an integer N and an array arr[ ] of size N, the task is to find the maximum jumps to reach the end of the array given the constraint that from index i can make arr[i] jumps and reach the position i+arr[i]. Examples: Input: N = 5, arr[] = {2, 3, 5, 7, 9}Output: 12 Explanation:At index 0 make 2 jumps and move to index 2 and make 5 jumps after t
6 min read
Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps
Given an array arr[] of integers, where the ith integer represents the position where an island is present, and an integer k (1 ? k &lt; N). A person is standing on the 0th island and has to reach the last island, by jumping from one island to another in exactly k jumps, the task is to find the minimum of the maximum length of a jump a person will
9 min read
Minimum cost to reach the end of the array with maximum jumps of length K
Given an array arr[] of size N and an integer K, one can move from an index i to any other index j such that j ? i+k. The cost of being at any index 'i', is arr[i]. The task is to find the minimum cost to reach the end of the array starting from index 0. Examples: Input : arr[] = {2, 4, 1, 6, 3}, K = 2Output: 6Explanation: Path can be taken as 2 -
11 min read
Find the number of jumps to reach X in the number line from zero
Given an integer X. The task is to find the number of jumps to reach a point X in the number line starting from zero. Note: The first jump made can be of length one unit and each successive jump will be exactly one unit longer than the previous jump in length. It is allowed to go either left or right in each jump. Examples: Input : X = 8Output : 4E
6 min read
Minimize cost to reach end of an array by two forward jumps or one backward jump in each move
Given an array arr[] consisting of N positive integers, the task is to find the minimum cost required to either cross the array or reach the end of the array by only moving to indices (i + 2) and (i - 1) from the ith index. Examples: Input: arr[] = {5, 1, 2, 10, 100}Output: 18Explanation:Optimal cost path (0 based indexing): 0 ? 2 ? 1 ? 3 ? 5Theref
11 min read
Minimum jumps from either end to reach largest and smallest character in given String
Given a string str, the task is to find the minimum number of moves required to reach lexicographically largest and smallest characters. In one move, a jump can be made from leftmost side or the rightmost side of given string. Examples: Input: str = AEDCB, N = 5 Output: 2Explanation: take two steps from leftmost side to reach A and E Input: str = B
6 min read
Minimum jumps to reach end of the array with given conditions
Given an array A[], the task is to print the minimum number of jumps needed to reach the last element of A[] starting from the first element. If it is impossible to reach the last element print -1. A jump can be made from index i to j if all the below conditions are met: i &lt; jA[i] &gt;= A[j]There must be no elements between index i and j or all
6 min read
Minimum number of Fibonacci jumps to reach end
Given an array of 0s and 1s, If any particular index i has value 1 then it is a safe index and if the value is 0 then it is an unsafe index. A man is standing at index -1(source) can only land on a safe index and he has to reach the Nth index (last position). At each jump, the man can only travel a distance equal to any Fibonacci Number. You have t
11 min read
Paths requiring minimum number of jumps to reach end of array
Given an array arr[], where each element represents the maximum number of steps that can be made forward from that element, the task is to print all possible paths that require the minimum number of jumps to reach the end of the given array starting from the first array element. Note: If an element is 0, then there are no moves allowed from that el
12 min read