The Puzzle: In a bag, you have W White balls and B Black balls. You perform the following operation repeatedly until only one ball remains:
- Pick two balls randomly.
- If they are the Same color, discard them and put a Black ball back into the bag.
- If they are Different colors, discard them and put a White ball back into the bag. What is the color of the last ball?
1. The Key Observation (The Invariant)
Let’s look at how the number of White balls (W) changes in each scenario:
- Pick 2 White: W decreases by 2. (You remove 2 White, put back 1 Black).
- Pick 2 Black: W remains the same. (You remove 2 Black, put back 1 Black).
- Pick 1 White, 1 Black: W remains the same. (You remove 1 White and 1 Black, but put back 1 White).
Crucial Point: W only ever decreases by 2 at a time. It never decreases by 1. This means the Parity (even or oddness) of the number of White balls never changes.
2. The Result
- If W is Even (initially): The last ball must be Black.
- If W is Odd (initially): The last ball must be White.
Interview-Focused Questions
Q: Why don’t we track the Black balls?
A: Because the number of Black balls (B) changes in a way that doesn’t have a preserved parity. In some steps B increases, in others it decreases by 1. The White ball parity is the only “Invariant” that can guide us to the finish line.
Q: What if I start with 0 White balls?
A: Then W=0 (which is even). Following the rule, the last ball will be Black. This makes sense: every operation will just consume Black balls and replace them with another Black ball until only one is left.
Key Takeaway
This puzzle is a great example of an Invariant. In software engineering and algorithms, finding the property that never changes during a set of operations is often the key to proving correctness.
Premium Content
Unlock Last Ball Color and all premium lessons with a subscription.
From ₹199.99/year — See plans