780. Reaching Points
Problem Description
A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).
Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) into (tx, ty). Otherwise, return False.
Examples:
Example 1:
Input: sx = 1, sy = 1, tx = 3, ty = 5 Output: true Explanation: One series of moves that transforms the starting point to the target is: (1, 1) -> (1, 2) (1, 2) -> (3, 2) (3, 2) -> (3, 5)
Example 2:
Input: sx = 1, sy = 1, tx = 2, ty = 2 Output: false
Example 3:
Input: sx = 1, sy = 1, tx = 1, ty = 1 Output: true
Constraints:
- 1 ≤ sx, sy, tx, ty ≤ 10^9
Python Solution
class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
while tx >= sx and ty >= sy:
if tx == sx and ty == sy:
return True
if tx > ty:
if ty == sy:
return (tx - sx) % ty == 0
tx %= ty
else:
if tx == sx:
return (ty - sy) % tx == 0
ty %= tx
return False
Implementation Notes:
- Uses reverse simulation approach
- Key insight: work backwards from target to start
- Time complexity: O(log max(tx, ty))
- Space complexity: O(1)
Java Solution
class Solution {
public boolean reachingPoints(int sx, int sy, int tx, int ty) {
while (tx >= sx && ty >= sy) {
if (tx == sx && ty == sy) {
return true;
}
if (tx > ty) {
if (ty == sy) {
return (tx - sx) % ty == 0;
}
tx %= ty;
} else {
if (tx == sx) {
return (ty - sy) % tx == 0;
}
ty %= tx;
}
}
return false;
}
}
C++ Solution
class Solution {
public:
bool reachingPoints(int sx, int sy, int tx, int ty) {
while (tx >= sx && ty >= sy) {
if (tx == sx && ty == sy) {
return true;
}
if (tx > ty) {
if (ty == sy) {
return (tx - sx) % ty == 0;
}
tx %= ty;
} else {
if (tx == sx) {
return (ty - sy) % tx == 0;
}
ty %= tx;
}
}
return false;
}
};
JavaScript Solution
function reachingPoints(sx, sy, tx, ty) {
while (tx >= sx && ty >= sy) {
if (tx === sx && ty === sy) {
return true;
}
if (tx > ty) {
if (ty === sy) {
return (tx - sx) % ty === 0;
}
tx %= ty;
} else {
if (tx === sx) {
return (ty - sy) % tx === 0;
}
ty %= tx;
}
}
return false;
}
C# Solution
public class Solution {
public bool ReachingPoints(int sx, int sy, int tx, int ty) {
while (tx >= sx && ty >= sy) {
if (tx == sx && ty == sy) {
return true;
}
if (tx > ty) {
if (ty == sy) {
return (tx - sx) % ty == 0;
}
tx %= ty;
} else {
if (tx == sx) {
return (ty - sy) % tx == 0;
}
ty %= tx;
}
}
return false;
}
}
Implementation Notes:
- Uses reverse simulation approach
- Key insight: work backwards from target to start
- Time complexity: O(log max(tx, ty))
- Space complexity: O(1)