#2543

Check if Point Is Reachable

Hard
MathNumber TheoryGreedy AlgorithmsMathematical Induction
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log(max(targetX, targetY)))
Space
O(1)
O(1)
💡

Intuition

Time O(log(max(targetX, targetY)))Space O(1)

Instead of exploring all paths, we can work backwards from (targetX, targetY) to (1, 1). By applying reverse operations, we can determine if we can reach the starting point. This significantly reduces the number of checks needed.

⚙️

Algorithm

3 steps
  1. 1Step 1: While targetX > 1 and targetY > 1, apply reverse operations: if targetX > targetY, set targetX = targetX - targetY; otherwise, set targetY = targetY - targetX.
  2. 2Step 2: If either targetX or targetY is even, divide it by 2 if possible.
  3. 3Step 3: If we reach (1, 1), return true; otherwise, return false.
solution.py7 lines
1def canReach(targetX, targetY):
2    while targetX > 1 and targetY > 1:
3        if targetX > targetY:
4            targetX -= targetY
5        else:
6            targetY -= targetX
7    return targetX == 1 or targetY == 1

Complexity note: The time complexity is O(log(max(targetX, targetY))) because each operation effectively reduces one of the coordinates, leading to logarithmic steps to reach (1, 1). The space complexity is O(1) since we are using a constant amount of space.

  • 1The ability to reverse operations allows for a more efficient solution.
  • 2Understanding the relationship between the coordinates helps in determining reachability.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.