Problem Description
You are given an infinite grid and start at point (1, 1). In one step you may move from (x, y) to one of these points:
- (x, y - x)
- (x - y, y)
- (2 * x, y)
- (x, 2 * y)
Determine if you can reach the target point (targetX, targetY) from (1,1) using a finite sequence of these moves.
Key Insights
- The subtraction moves (x, y - x) and (x - y, y) preserve the greatest common divisor (gcd) of the coordinates.
- The doubling moves (2x, y) and (x, 2y) may multiply the gcd by 1 or 2.
- Starting at (1,1) (where gcd = 1, which is 2^0) the gcd of any reachable point must be a power of 2.
- Therefore, (targetX, targetY) is reachable if and only if gcd(targetX, targetY) is a power of 2.
Space and Time Complexity
Time Complexity: O(log(min(targetX, targetY))) due to the Euclidean algorithm for computing gcd.
Space Complexity: O(1)
Solution
This solution leverages the invariant that subtracting one coordinate from the other does not change their gcd, and doubling moves can only multiply the gcd by a factor of 2. Since the start point (1,1) has a gcd of 1 (2^0), the target point (targetX, targetY) must have a gcd that is a power of 2 to be reachable. We use the Euclidean algorithm to compute the gcd and then check if it is a power of 2 by ensuring it has exactly one set bit in its binary representation (i.e., n & (n-1) == 0).