Check if Point Is Reachable - Problem

There exists an infinitely large grid. You are currently at point (1, 1), and you need to reach the point (targetX, targetY) using a finite number of steps.

In one step, you can move from point (x, y) to any one of the following points:

  • (x, y - x)
  • (x - y, y)
  • (2 * x, y)
  • (x, 2 * y)

Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position, return true if you can reach the point from (1, 1) using some number of steps, and false otherwise.

Input & Output

Example 1 — Reachable Point
$ Input: targetX = 6, targetY = 9
Output: false
💡 Note: GCD(6,9) = 3, which is not a power of 2, so point (6,9) cannot be reached from (1,1)
Example 2 — Power of 2 GCD
$ Input: targetX = 4, targetY = 6
Output: true
💡 Note: GCD(4,6) = 2, which is a power of 2, so point (4,6) can be reached from (1,1)
Example 3 — Same Point
$ Input: targetX = 1, targetY = 1
Output: true
💡 Note: We start at (1,1), so it's immediately reachable with 0 steps

Constraints

  • 1 ≤ targetX, targetY ≤ 109

Visualization

Tap to expand
Check if Point Is Reachable INPUT S T X axis Y axis targetX = 6 targetY = 9 Start: (1, 1) Target: (6, 9) Moves: (x,y-x), (x-y,y) (2x,y), (x,2y) ALGORITHM STEPS 1 Reverse Operations Work backwards from target to start point (1,1) 2 GCD Insight Subtract ops = GCD ops Divide by 2 = halving 3 Key Formula Reachable if and only if GCD(targetX,targetY)=2^k 4 Calculate GCD(6, 9) = 3 3 is NOT a power of 2 GCD(6, 9): 9 = 1*6 + 3 6 = 2*3 + 0 GCD = 3 (not 2^k) Powers of 2: 1,2,4,8,16... FINAL RESULT (1,1) (6,9) UNREACHABLE false Cannot reach (6, 9) from (1, 1) using the given operations. GCD(6,9) = 3 3 is not a power of 2 Key Insight: The point (targetX, targetY) is reachable from (1, 1) if and only if GCD(targetX, targetY) is a power of 2. This is because subtraction operations behave like GCD, and multiplication by 2 only introduces factors of 2. Since GCD(6, 9) = 3, which has an odd factor, we cannot reach (6, 9). The answer is false. TutorialsPoint - Check if Point Is Reachable | Optimal Solution (GCD Power of 2)
Asked in
Google 15 Meta 8
8.5K Views
Medium Frequency
~25 min Avg. Time
245 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