KatInterview

Splitting Tokens: Will a Bucket Ever Run Dry?

Math & Bit ManipulationAuto-graded · 26 test cases
HardAuto-gradedMath & Bit Manipulationmathbit-manipulationnumber-theory

Last updated

Tests whether a candidate can identify a modular-arithmetic invariant to avoid simulating an exponentially long process.

Problem

You have two buckets holding tokens. Bucket A starts with a tokens and Bucket B starts with b tokens. Neither bucket is empty at the start.

Each turn, you are forced to make exactly one move:

  • Count the tokens in the smaller bucket — call that number s. Transfer exactly s tokens from the larger bucket into the smaller one. The smaller bucket now holds 2s tokens.
  • If both buckets hold the same number of tokens, pour all tokens from one bucket into the other (it doesn't matter which direction — the resulting pair of sizes is the same either way).

The total number of tokens across both buckets is fixed throughout — tokens are only moved, never created or destroyed. The move is always forced, so the sequence of states is entirely determined by the starting values.

Your task: decide whether this process will ever produce a bucket containing zero tokens.

Return True if some bucket empties after a finite number of moves. Return False if the process continues indefinitely, cycling through states without ever emptying a bucket.

Important note on efficiency

A direct step-by-step simulation is not an acceptable solution. The number of moves before a cycle is detected can be as large as the total number of tokens, which may be up to 2 × 10^9. Your solution must run in O(log(a + b)) time.

Constraints

  • 1 <= a, b <= 10^9
  • Both a and b are positive integers.

Examples

Example 1

Input: bucket_empties(3, 5)

Output: True

Example 2

Input: bucket_empties(2, 6)

Output: True

Example 3

Input: bucket_empties(1, 24)

Output: False

Example 4

Input: bucket_empties(1, 23)

Output: False

Hints

Hint 1

The total T = a + b never changes. Track just one bucket's size x; the other is always T - x. Write out what happens to x in one move and see if you can express it as a modular operation.

Hint 2

After each move, x becomes 2x mod T. So after k moves the first bucket holds (2^k * a) mod T. A bucket empties exactly when this residue hits 0 — that is, when T divides 2^k * a for some k >= 1.

Hint 3

Factor T as 2^q * m where m is odd. Doubling can supply any power of two, but it can never introduce a new odd factor. So T | 2^k * a requires m | a. Check whether the odd part of T divides a — that's the whole test.