Skip to content
Problem 780 · LeetCode 780(opens in a new tab)

Reaching Points

HardMath

You start at the point (sx, sy). In one move, a point (x, y) can become either (x + y, y) or (x, x + y): one coordinate grows by the other.

Return true if some sequence of moves (possibly none) reaches the point (tx, ty), and false otherwise.

Example 1

Input:  sx = 1, sy = 2, tx = 19, ty = 7
Output: true
Why:    (1, 2) → (3, 2) → (5, 2) → (5, 7) → (12, 7) → (19, 7)
2 more examples and the constraints

Example 2

Input:  sx = 1, sy = 2, tx = 4, ty = 4
Output: false
Why:    a move always leaves the two coordinates different

Example 3

Input:  sx = 6, sy = 9, tx = 6, ty = 9
Output: true
Why:    zero moves are allowed

Constraints

  • 1 ≤ sx, sy, tx, ty ≤ 10⁹

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Walk back by subtractionO(max(tx, ty))
  2. Walk back by moduloO(log max)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for tx, ty ≤ 10⁹Verdict
Walk back by subtractionO(max(tx, ty))
Up to a billion steps on skewed targets
Walk back by moduloO(log max)
Best; about 45 steps at most

tx, ty = the target point; max = the larger coordinate.

Edge cases to test

  • Target equals start. Zero moves: true.
  • Equal coordinates. (4, 4) can only be reached if it is the start itself, because a move makes the two different.
  • Target below the start. Coordinates never shrink, so any target coordinate below its start means false.
  • One coordinate already matches. From (3, 2) to (3, 17): 17 − 2 = 15 is a multiple of 3, so true.
  • Huge, skewed target. (1, 1) to (10⁹, 1) needs the modulo shortcut and the final divisibility check.

Common mistakes

  • Searching forward with recursion, which branches two ways per move and never ends in time.
  • Applying the modulo when one coordinate already equals its start value, which overshoots below the start.
  • Forgetting that tx == ty (above the start) can never be reached, which loops forever with subtraction.

How to talk through it

  1. 1Clarify. Are all values positive? Can zero moves count? (Yes to both.)
  2. 2Go backwards. The larger coordinate is the one that changed last, so each point has exactly one parent.
  3. 3Spot the slowdown. Subtracting 1 from a billion is a billion steps; repeated subtraction is a modulo.
  4. 4Guard the end. Use the modulo only while both are above the start, then check the leftover gap divides evenly.
  5. 5Test out loud. Try (1, 2) → (19, 7), (1, 2) → (4, 4), and (1, 1) → (10⁹, 1).
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?