Reaching Points - 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).

Input & Output

Example 1 — Reachable Target
$ Input: sx = 1, sy = 1, tx = 3, ty = 5
Output: true
💡 Note: Path exists: (1,1) → (1,2) → (3,2) → (3,5). We can apply operations (1,1+1)=(1,2), then (1+2,2)=(3,2), then (3,3+2)=(3,5).
Example 2 — Unreachable Target
$ Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: false
💡 Note: From (1,1) we can only reach (1,2) or (2,1), but never (2,2). Both coordinates cannot increase simultaneously.
Example 3 — Same Point
$ Input: sx = 1, sy = 1, tx = 1, ty = 1
Output: true
💡 Note: Source and target are the same point, so no operations needed.

Constraints

  • 1 ≤ sx, sy, tx, ty ≤ 109

Visualization

Tap to expand
Reaching Points - Optimal Solution INPUT Starting Point (sx, sy) (1, 1) Target Point (tx, ty) (3, 5) Allowed Operations: (x, y) --> (x, x+y) (x, y) --> (x+y, y) sx=1, sy=1 tx=3, ty=5 ALGORITHM STEPS 1 Work Backwards From (tx,ty) to (sx,sy) 2 Use Modulo If tx>ty: tx = tx % ty 3 Repeat Until tx<=sx OR ty<=sy 4 Check Result Verify reachability Backward Trace: (3,5): 5>3, ty=5%3=2 (3,2): 3>2, tx=3%2=1 (1,2): ty>sy, check: (2-1)%1==0? YES Reachable: TRUE FINAL RESULT Valid Path Found: (1, 1) +y to x (2, 1) +y to x (3, 1) +x to y (3, 4) (3, 5) OK Output: true Key Insight: Working backwards from target to source is efficient because each step is deterministic. Using modulo instead of repeated subtraction gives O(log(max(tx,ty))) time complexity. Forward approach would require exponential branching; backward approach is linear. TutorialsPoint - Reaching Points | Optimal Solution (Work Backwards with Modulo)
Asked in
Google 15 Facebook 8
28.0K Views
Medium Frequency
~25 min Avg. Time
842 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