Reaching Points LeetCode Solution

Last updated on October 9th, 2024 at 06:24 pm

Here, We see Reaching Points LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Array

Level of Question

Hard

Reaching Points LeetCode Solution

Reaching Points LeetCode Solution

Problem Statement

Given four integers sxsytx, 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 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

1. Reaching Points Solution C++

class Solution {
public:
    bool reachingPoints(int sx, int sy, int tx, int ty) {
        while(sx < tx && sy < ty){
            if(tx > ty) tx = tx%ty;
            else ty = ty%tx;
        }
        if(sx == tx && sy<= ty && (ty-sy)%sx == 0) return true;
        if(sy == ty && sx <= tx && (tx-sx)%sy == 0) return true;
        return false;        
    }
};

2. Reaching Points Solution Java

class Solution {
    public boolean reachingPoints(int sx, int sy, int tx, int ty) {
        while (tx >= sx && ty >= sy) {
            if (tx == ty) break;
            if (tx > ty) {
                if (ty > sy) tx %= ty;
                else return (tx - sx) % ty == 0;
            } else {
                if (tx > sx) ty %= tx;
                else return (ty - sy) % tx == 0;
            }
        }
        return (tx == sx && ty == sy);        
    }
}

3. Reaching Points Solution JavaScript

var reachingPoints = function (sx, sy, tx, ty) {
    if (sx > tx || sy > ty) return false;
    if (sx === tx) return (ty - sy) % sx === 0;
    if (sy === ty) return (tx - sx) % sy === 0;
    if (tx > ty) return reachingPoints(sx, sy, tx % ty, ty);
    else if (tx < ty) return reachingPoints(sx, sy, tx, ty % tx);
    else return false;
}

4. Reaching Points Solution Python

class Solution(object):
    def reachingPoints(self, sx, sy, tx, ty):
        if tx==0 or ty==0: return (sx, sy)==(tx, ty)
        while not (sx==tx and sy==ty):
            if sx>tx or sy>ty: return False
            elif tx==ty: return ((0, ty)==(sx, sy) or (tx, 0)==(sx, sy))
            
            if ty>tx: 
                if tx==sx: return (ty-sy)%sx==0
                ty%=tx
            else: 
                if ty==sy: return (tx-sx)%sy==0
                tx%=ty
                     
        return True
Scroll to Top