981. Reach the Point

Hard7.5 points estimatedMathsNumber Theory3 hints

A drone sits at grid position (sx, sy). In one move it may jump from (x, y) to either (x + y, y) or (x, x + y). All coordinates are positive integers, so every move strictly grows one of the two coordinates and never shrinks either of them.

Return true if the drone can reach exactly (tx, ty) after zero or more moves, and false otherwise. The numbers can be as large as a billion, so trying every sequence of moves forward, or counting them one at a time, is far too slow. Zero moves is allowed, so the start itself counts as reachable.

Example 1

Input:
sx = 2sy = 3tx = 2ty = 17
Output:
true
Explanation:

Repeatedly adding the first value to the second moves (2, 3) to (2, 5), (2, 7), ... and after 7 moves reaches (2, 17), so the answer is true.

Example 2

Input:
sx = 3sy = 4tx = 10ty = 6
Output:
false
Explanation:

Undoing moves from (10, 6) gives (4, 6) and then (4, 2); the first coordinate 4 and the second 2 can never get back to (3, 4), so the answer is false.

Example 3

Input:
sx = 4sy = 4tx = 4ty = 4
Output:
true
Explanation:

The start already equals the target, so zero moves are needed and the answer is true.

Constraints

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

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(log(max(tx, ty)))
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…