Check if Point is Reachable
Problem​
There exists an infinitely large grid. You are currently at point , and you need to reach the point using a finite number of steps.
In one Step, you can move from point to any one of the following points:
Given two integers and representing the X-coordinate and Y-coordinate of your final position, return if you can reach the point from using some number of steps, and otherwise.
Examples​
Example 1:
Input: targetX = 6, targetY = 9
Output: false
Explanation: It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned.
Example 2:
Input: targetX = 4, targetY = 7
Output: true
Explanation: You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).
Constraints​
1 <= targetX, targetY <= 10^9
Approach​
To solve the problem, we need to understand the nature of the allowed moves:
These moves suggest that if we can reach a certain point '(x, y)', we can generate other points by specific transformations. By analyzing the moves:
-
The first two moves involve subtraction, reducing one coordinate.
-
The last two moves involve multiplication by .
We can reverse the logic to check whether we can reach from . This reversal involves:
-
Checking if or can be divided by (to reverse the multiplication).
-
Checking if one coordinate can be reduced by subtracting the other.
By reversing the operations, we trace the problem back to whether can be reduced to .
The key insight here is that we only need to check if 'gcd(targetX, targetY)' is a power of . This is because if both and share a common factor other than , it won't be possible to reach .
Solution for Check if Point is Reachable​
The given problem involves reaching a target point from the starting point using a set of allowed moves. The challenge is to determine whether it's possible to reach the target using these moves.
Code in Java​
class Solution {
public boolean isReachable(int targetX, int targetY) {
return Integer.bitCount(gcd(targetX, targetY)) == 1;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
Complexity Analysis​
Time Complexity: ​
Reason: Calculating the gcd of two numbers takes time using the Euclidean algorithm.
Space Complexity: ​
Reason: The space complexity is since we are using a constant amount of extra space for computation (ignoring the space used by the recursive stack of the gcd function, which is logarithmic in terms of the depth of the recursion).
References
- LeetCode Problem: Check if Point is Reachable
- Solution Link: Check if Point is Reachable Solution on LeetCode
- Authors LeetCode Profile: Vivek Vardhan