Reference: LeetCode
Difficulty: Hard
Problem
A move consists of taking a point
(x, y)
and transforming it to either(x, x+y)
or(x+y, y)
.
Given a starting point
(sx, sy)
and a target point(tx, ty)
, returnTrue
if and only if a sequence of moves exists to transform the point(sx, sy)
to(tx, ty)
. Otherwise, returnFalse
.
Note: sx
, sy
, tx
, ty will all be integers in the range [1, 10^9]
.
Example:
1 | Input: sx = 1, sy = 1, tx = 3, ty = 5 |
Analysis
Brute-Force
1 | public boolean reachingPoints(int sx, int sy, int tx, int ty) { |
Time: $O(2^{tx + ty})$, a loose bound found by considering every move as (x, y) -> (x + 1, y)
or (x, y) -> (x, y + 1)
.
Space: $O(tx + ty)$, the size of call stack.
Work Backwards (Naive Variant)
From LeetCode solution:
1 | // / (x + y, y) |
Time: $O(\max{(tx, ty)})$. If say ty = 1
, we could do subtraction for tx
times.
Space: $O(1)$
Work Backwards (Modulo Variant)
1 | public boolean reachingPoints(int sx, int sy, int tx, int ty) { |
Time: $O(\log{\max{(tx, ty)}})$
Space: $O(1)$