HardNo. 0780

Reaching Points — LeetCode 780 Python Solution

Topics
Math
Reading time
3 min

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

PythonSolution
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 False

Complexity

Time
O(n) or O(1)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0775Global and Local InversionsMedium
0789Escape The GhostsMedium
0002Add Two NumbersMedium
0007Reverse IntegerMedium
0009Palindrome NumberEasy
0043Multiply StringsMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.