KatInterview

Can a Starting Pair Grow Into a Goal Pair by Summing Coordinates?

Math & Bit ManipulationAuto-graded · 25 test cases
HardAuto-gradedMath & Bit Manipulationmatheuclidean-algorithmreverse-thinking

Last updated

Decide whether a goal pair is reachable from a start pair by replacing one coordinate with the sum of both, using a reverse walk with Euclid-style modulo jumps for values up to 10^9.

You are given a start pair of positive integers (a, b) and a goal pair (c, d).

A single operation takes the current pair (x, y) and replaces it with one of two pairs:

  • (x + y, y): the first coordinate becomes the sum of both, or
  • (x, x + y): the second coordinate becomes the sum of both.

Determine whether (c, d) can be produced from (a, b) by applying the operation some number of times (possibly zero).

Return True if the goal pair is reachable and False otherwise.

Details

  • Pairs are ordered, so (2, 3) and (3, 2) are different pairs.
  • Applying zero operations is allowed. If (a, b) == (c, d), the answer is True.
  • Both coordinates are always positive, so every operation strictly increases exactly one coordinate.

Parameters

  • a, b: the start pair, first and second coordinate.
  • c, d: the goal pair, first and second coordinate.

Returns

A boolean: True if (c, d) is reachable from (a, b), otherwise False.

Constraints

  • 1 <= a, b, c, d <= 10^9
  • All inputs fit in a signed 32-bit integer.
  • A solution that tries every forward sequence of operations will be too slow.

Examples

Example 1

Input: can_grow_to(1, 1, 3, 5)

Output: True

Example 2

Input: can_grow_to(1, 1, 2, 2)

Output: False

Example 3

Input: can_grow_to(1, 1, 1, 1)

Output: True

Hints

Hint 1

Going forward, every pair has two children. Going backward, look at which coordinate is larger in the goal pair: how many different pairs could have produced it?

Hint 2

Each pair has at most one predecessor: subtract the smaller coordinate from the larger one. If the coordinates are equal, there is no valid predecessor. Peeling off one subtraction at a time is too slow for values near 10^9, so think about how Euclid's algorithm batches subtractions with a modulo.

Hint 3

A plain modulo can jump over the start pair. When the coordinate being reduced already matches its start value, the other coordinate must reach its start value by subtracting that fixed amount some whole number of times, which is a divisibility check. Otherwise the modulo is safe.