KatInterview

Pair Growth by Adding One Coordinate to the Other

Math & Bit ManipulationAuto-graded · 24 test cases
MediumAuto-gradedMath & Bit Manipulationmatheuclidean-algorithmreverse-simulation

Last updated

Decide whether a positive integer pair can grow into a target pair by repeatedly adding one coordinate to the other, using reverse-step reasoning and Euclid-style reduction.

You start with a pair of positive integers (a, b). In one step you may choose either of these updates:

  • Replace the first number with the sum of both: (x, y) -> (x + y, y).
  • Replace the second number with the sum of both: (x, y) -> (x, x + y).

You may apply any number of steps (including zero) in any order.

Given the starting pair (a, b) and a target pair (c, d), return True if the target can be produced from the start, and False otherwise.

Details

  • The arguments are a, b, c, d, in that order. (a, b) is the start and (c, d) is the target.
  • Applying zero steps is allowed, so if (a, b) == (c, d) the answer is True.
  • Both numbers stay positive at all times, and neither number ever decreases.
  • Return a boolean.

Constraints

  • 1 <= a, b, c, d <= 1000
  • All inputs are integers.

Examples

Example 1

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

Output: True

Example 2

Input: can_grow_to_pair(1, 1, 2, 2)

Output: False

Example 3

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

Output: False

Example 4

Input: can_grow_to_pair(2, 3, 2, 3)

Output: True

Hints

Hint 1

Going forward you have two choices every step, but going backward from the target there is only one possible previous pair. Ask which coordinate must have been updated last.

Hint 2

If c > d, the previous pair must have been (c - d, d); if d > c, it must have been (c, d - c). If c == d, no step could have produced it, so it is reachable only if it already equals the start.

Hint 3

Repeated subtraction is just the Euclidean algorithm, so you can use modulo to speed it up. Be careful: when one coordinate already matches the start, do not jump with modulo. Instead check whether the other coordinate differs from its start value by a multiple of the matching coordinate.