Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Last Ball Color
INTERVIEWPUZZLE

Last Ball Color

Use probability and counting reasoning to determine the possible color of the final ball under the given conditions.

The Puzzle: In a bag, you have WW White balls and BB Black balls. You perform the following operation repeatedly until only one ball remains:

  1. Pick two balls randomly.
  2. If they are the Same color, discard them and put a Black ball back into the bag.
  3. 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 (WW) changes in each scenario:

  • Pick 2 White: WW decreases by 2. (You remove 2 White, put back 1 Black).
  • Pick 2 Black: WW remains the same. (You remove 2 Black, put back 1 Black).
  • Pick 1 White, 1 Black: WW remains the same. (You remove 1 White and 1 Black, but put back 1 White).

Crucial Point: WW 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 WW is Even (initially): The last ball must be Black.
  • If WW 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 (BB) changes in a way that doesn’t have a preserved parity. In some steps BB 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=0W=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.

My Private Notes

Notes are auto-saved locally to this device.