Reaching Points - Problem

You're given a starting point (sx, sy) and a target point (tx, ty) on a 2D coordinate plane. Your goal is to determine if you can transform the starting point into the target point using a specific set of operations.

The allowed operations are:

  • From point (x, y), you can move to (x + y, y) - add y-coordinate to x-coordinate
  • From point (x, y), you can move to (x, x + y) - add x-coordinate to y-coordinate

Example: Starting from (1, 1), you could reach (3, 2) by: (1, 1) โ†’ (1, 2) โ†’ (3, 2)

Return true if it's possible to reach the target point, false otherwise.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, 1, 3, 5]
โ€บ Output: true
๐Ÿ’ก Note: We can reach (3,5) from (1,1): (1,1) โ†’ (1,2) โ†’ (3,2) โ†’ (3,5). Each step uses one of the allowed operations.
example_2.py โ€” Impossible Case
$ Input: [1, 1, 2, 2]
โ€บ Output: false
๐Ÿ’ก Note: From (1,1), we can reach (1,2), (2,1), (2,3), (3,2), etc., but never (2,2). The operations always increase one coordinate significantly.
example_3.py โ€” Same Point
$ Input: [1, 1, 1, 1]
โ€บ Output: true
๐Ÿ’ก Note: The starting point is already the target point, so no operations are needed.

Visualization

Tap to expand
The Mathematical Ladder ProblemโŒ Forward Approach (Slow)(1,1)Exponential paths!โœ… Reverse Approach (Fast)(tx,ty)(sx,sy)๐ŸŽฏ Key Mathematical InsightOperations: (x,y) โ†’ (x+y,y) or (x,x+y)Reverse: If tx > ty, then previous point was (tx-ty, ty) or (tx%ty, ty)Modular arithmetic lets us skip multiple identical steps!Time Complexity: O(log(max(tx,ty))) vs O(2^(tx+ty))
Understanding the Visualization
1
Forward Explosion
Going forward creates exponentially many paths - like exploring every possible climbing route
2
Reverse Insight
Working backwards, there's only one way to reach each rung - much more efficient!
3
Modular Magic
When coordinates differ greatly, use modular arithmetic to skip many identical steps
4
Convergence
Keep working backwards until you reach the start or prove it's impossible
Key Takeaway
๐ŸŽฏ Key Insight: Working backwards with modular arithmetic transforms an exponential problem into a logarithmic one, making it efficient even for coordinates up to 10^9.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(2^(tx+ty))

Each step can branch into 2 possibilities, leading to exponential growth

n
2n
โœ“ Linear Growth
Space Complexity
O(2^(tx+ty))

Recursion stack and memoization table can grow exponentially

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค sx, sy, tx, ty โ‰ค 109
  • Coordinates are positive integers
  • Operations only increase coordinate values
  • Must handle large coordinate differences efficiently
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 15
27.4K Views
Medium Frequency
~25 min Avg. Time
896 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen