KatInterview

Reachability Under Sum-Replacement Moves on a Grid

Math & Bit ManipulationAuto-graded · 26 test cases
HardAuto-gradedMath & Bit Manipulationmatheuclidean-algorithmmodulo

Last updated

Decide whether one positive integer point can become another by repeatedly replacing a coordinate with the coordinate sum, for values up to 10^18, by reversing moves with modulo.

Reaching a Point by Sum Moves

You are standing at a point (x, y) on a grid, where x and y are positive integers. In one move, you may do exactly one of the following:

  • Replace x with x + y, giving (x + y, y).
  • Replace y with x + y, giving (x, x + y).

You are given a starting point (start_x, start_y) and a goal point (target_x, target_y). Return True if the goal can be reached from the start using zero or more moves, and False otherwise.

Zero moves is allowed, so if the start and goal are the same point, the answer is True.

Input

  • start_x, start_y: the coordinates of the starting point.
  • target_x, target_y: the coordinates of the goal point.

Output

  • A boolean: True if the goal is reachable from the start, False otherwise.

Constraints

  • All four values are integers.
  • 1 <= start_x, start_y, target_x, target_y <= 10^18
  • The solution must be fast enough for values near 10^18, so step-by-step simulation of individual moves will not finish in time.

Examples

Example 1

Input: is_reachable(1, 2, 3, 5)

Output: True

Example 2

Input: is_reachable(1, 1, 2, 2)

Output: False

Hints

Hint 1

Searching forward branches into two options every step. Think about whether, from the goal, there is only one way the last move could have happened.

Hint 2

Since all coordinates stay positive, the larger coordinate of a point must have been produced by adding the smaller one to it. Undoing a move is therefore deterministic, except when both coordinates are equal.

Hint 3

Undoing moves one at a time can take about 10^18 steps. A long run of identical undo steps can be collapsed with the modulo operator, as in Euclid's algorithm. Be careful not to skip past the start coordinate: once one coordinate matches the start, check divisibility instead of taking a full modulo.