LeetCode 780: Reaching Points Solution

Master LeetCode problem 780 (Reaching Points), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

780. Reaching Points

Hard

Problem Explanation

Explanation

To solve this problem, we can work backwards from the target point (tx, ty) to the starting point (sx, sy). We can keep subtracting the smaller of the two coordinates from the larger one until we reach the starting point or go out of bounds. If we reach the starting point, we return true; otherwise, we return false.

Algorithm

  1. While tx >= sx and ty >= sy:
    • If tx == sx and ty == sy, return true.
    • If tx > ty, subtract ty from tx.
    • If ty > tx, subtract tx from ty.
  2. If we go out of bounds, return false.

Time Complexity

The time complexity of this algorithm is O(log(max(tx, ty))) because at each step, we are reducing one of the coordinates by the other one.

Space Complexity

The space complexity of this algorithm is O(1) as we are using constant extra space.

Solution Code

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) {
                tx -= ty;
            } else {
                ty -= tx;
            }
        }
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 780 (Reaching Points)?

This page provides optimized solutions for LeetCode problem 780 (Reaching Points) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 780 (Reaching Points)?

The time complexity for LeetCode 780 (Reaching Points) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 780 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 780 in Java, C++, or Python.

Back to LeetCode Solutions