Check if Point Is Reachable Problem
Description
LeetCode Problem 2543.
There exists an infinitely large grid. You are currently at point (1, 1), and you need to reach the point (targetX, targetY) using a finite number of steps.
In one step, you can move from point (x, y) to any one of the following points:
(x, y - x)(x - y, y)(2 * x, y)(x, 2 * y)
Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position, return true if you can reach the point from (1, 1) using some number of steps, and false otherwise.
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
Solution
Approach: Mathematics
The first two moves, (x, y - x) and (x - y, y), keep gcd(x, y) unchanged, and the last two moves, (2x, y) and (x, 2y), can only multiply it by 2. Starting from (1, 1) with gcd 1, the gcd of any reachable point is therefore a power of two.
The converse also holds. Work backwards from the target, where the moves become (x, x + y), (x + y, y), (x / 2, y) and (x, y / 2). Divide out factors of two while x or y is even, so both end up odd. If x != y, say x > y, then x + y is even and (x + y) / 2 < x, so we can shrink x. Repeating this ends at x = y, which is a power of two exactly when the original gcd was one, and that point reduces to (1, 1).
So the answer is whether gcd(targetX, targetY) is a power of two, checked with g & (g - 1) == 0.
Complexity: O(log(min(targetX, targetY))) time and O(1) extra space.
from math import gcd
class Solution:
def isReachable(self, targetX: int, targetY: int) -> bool:
x = gcd(targetX, targetY)
return x & (x - 1) == 0