#780
Reaching Points
HardMathMathematical OperationsGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log(max(tx, ty))) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log(max(tx, ty)))Space O(1)
Instead of trying to reach the target from the start point, we can reverse the operations and check if we can reach the starting point from the target. This is like retracing your steps on a map to see if you can get back to where you started.
⚙️
Algorithm
3 steps- 1Step 1: While tx and ty are greater than sx and sy, reverse the operations: if tx > ty, subtract ty from tx; otherwise, subtract tx from ty.
- 2Step 2: After reducing tx and ty, check if either tx equals sx and ty is greater than or equal to sy, or ty equals sy and tx is greater than or equal to sx.
- 3Step 3: If we can reach (sx, sy) from (tx, ty) using the reverse operations, return true; otherwise, return false.
solution.py9 lines
1# Full working Python code
2
3def canReach(sx, sy, tx, ty):
4 while tx > sx and ty > sy:
5 if tx > ty:
6 tx -= ty
7 else:
8 ty -= tx
9 return (tx == sx and ty >= sy and (ty - sy) % sx == 0) or (ty == sy and tx >= sx and (tx - sx) % sy == 0)ℹ
Complexity note: The complexity is O(log(max(tx, ty))) because we are effectively halving the larger of the two coordinates in each iteration, which leads to logarithmic time complexity.
- 1The operations are reversible, allowing us to work backwards from the target.
- 2The conditions for reaching the target involve modular arithmetic, which can simplify checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.