Reaching Points — LeetCode 780 Python Solution
- Problem
- #780
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise. The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).
Example
- 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:
Python solution
class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
while tx > sx and ty > sy and tx != ty:
if tx > ty:
tx %= ty
else:
ty %= tx
if tx == sx and ty == sy:
return True
if tx == sx:
return ty > sy and (ty - sy) % tx == 0
if ty == sy:
return tx > sx and (tx - sx) % ty == 0
return FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 780. Reaching Points is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 780. Reaching Points?
- LeetCode 780. Reaching Points is rated Hard on LeetCode.
- What topics does LeetCode 780. Reaching Points cover?
- LeetCode 780. Reaching Points is tagged Math on LeetCode.