Check if a given value can be reached from another value in a Circular Queue by K-length jumps
Given integers N, K, A, and B, check if it is possible to reach B from A in a circular queue of integers from 1 to N placed sequentially, by jumps of K length. In each move, If it is possible, then print “Yes”. Otherwise, print “No”.
Input: N = 5, A = 2, B = 1, K = 2
Explanation: 2 -> 4 -> 1. Therefore, it is possible to reach B from A.
Input: N = 9, A = 6, B = 5, K = 3
Approach: The idea to solve the problem is based on the following observations:
- For position A, and after t steps, the position of A is (A + K*t)%N.
- For position B, and after t steps, the position of B is (A + K*t)%N.
- It can be written as:
(A + K*t) = (N*q + B), where q is any positive integer
(A – B) = N*q – K*t
On observing the above equation (N*q – K*t) is divisible by GCD of N and K. Therefore, (A – B) is also divisible by GCD of N and K. Therefore, to reach B from A, (A – B) must be divisible by GCD(N, K).
Below is the implementation of the above approach:
Time Complexity: O(log(min(N, K))
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.