KatInterview

Determine if Two Coin Stacks Can Be Equalized by Doubling

Math & Bit ManipulationAuto-graded · 24 test cases
MediumAuto-gradedMath & Bit Manipulationmath-bitsnumber-theorybit-manipulation

Last updated

Determine if two initial quantities can reach equality through deterministic transfers that double the recipient stack.

You are given two stacks of coins containing a and b coins respectively.

You can perform a operation where coins are transferred from one stack to another. Specifically, you select one stack as the destination and transfer coins from the source stack into it. The number of coins transferred must equal the target stack's current size, effectively doubling the target stack's size. This operation is valid only if the source stack holds at least as many coins as the target stack.

Determine whether it is possible to make both stacks hold an equal number of coins after zero or more valid operations.

Constraints

  • 1 <= a, b <= 10^9

Examples

Example 1

Input: can_balance(3, 5)

Output: True

Example 2

Input: can_balance(1, 2)

Output: False

Example 3

Input: can_balance(2, 4)

Output: False

Example 4

Input: can_balance(7, 7)

Output: True

Hints

Hint 1

Observe that the sum `a + b` remains constant throughout any sequence of valid operations.

Hint 2

Because the transfer must double the recipient, only the smaller (or equal) stack can receive coins in a valid move, making the transition deterministic.

Hint 3

Examine the value of the first stack modulo `S = a + b` after each operation: `a` transforms to `(2 * a) % S`.