Problem Description
Given a starting point (sx, sy) and a target point (tx, ty), determine if it is possible to reach the target by repeatedly applying one of the two operations: (x, y) → (x, x+y) or (x, y) → (x+y, y).
Key Insights
- Instead of building up from (sx, sy) forwards, work backwards from (tx, ty) by reversing the operations.
- When both target coordinates are greater than the starting coordinates, you can use modulo arithmetic: subtract the smaller coordinate multiple times from the larger coordinate.
- After reducing one coordinate below or equal to the corresponding starting coordinate, check if the remaining difference is a valid multiple.
- Edge-case handling is critical when one coordinate exactly equals the starting coordinate.
Space and Time Complexity
Time Complexity: O(log(max(tx, ty))) – each loop iteration reduces one coordinate significantly using modulo. Space Complexity: O(1) – only a constant amount of extra space is used.
Solution
The solution works by reversing the allowed operations. Given (tx, ty), if both coordinates are larger than (sx, sy), then:
- If tx > ty, observe that the previous step might have been (tx - ty, ty). Instead of subtracting ty repeatedly, we can compute tx % ty.
- If ty > tx, compute ty % tx. Once one of the coordinates equals the starting coordinate, verify that the other coordinate can be reached by repeatedly adding the fixed coordinate. This check uses simple modular arithmetic. This backward approach is efficient given the problem constraints and avoids the exponential blowup that a recursive forward search would cause.