Blind Coin Partition for Matching Head Counts
Easy · Software Engineering Fundamentals · Data Scientist · Technical Screen
Problem Statement
In a pitch-black room, n coins indexed 0, 1, ..., n - 1 sit in a row. You cannot inspect which face any individual coin shows, though you know the total coin count n and the exact initial count h of coins facing heads (the remaining n - h coins face tails).
Implement split_coins_to_match_heads(n, h) to produce a blind partition-and-inversion plan. Partition every coin index 0 .. n - 1 across two disjoint groups ("pile1" and "pile2", which may differ in size or be empty) and select a list of distinct coin indices ("flip") whose faces are inverted (heads <-> tails). Once the coins in "flip" are inverted, "pile1" and "pile2" must finish with the exact same count of heads-up coins for every valid initial placement of the h heads.
To make the output canonical, assign a contiguous prefix [0, 1, ..., k - 1] (of your chosen size k) to "pile1", assign the remaining suffix [k, k + 1, ..., n - 1] to "pile2", and list "flip" in ascending index order:
def split_coins_to_match_heads(n: int, h: int) -> Dict[str, List[int]]:
...
If n < 0, h < 0, or h > n, raise ValueError.
Examples
Example 1
Input: n = 5, h = 2
Output: {"pile1": [0, 1], "pile2": [2, 3, 4], "flip": [0, 1]}
Explanation: Suppose x of the 2 initial heads sit among [0, 1]. Then "pile2" keeps 2 - x untouched heads, while "pile1" starts with 2 - x tails that invert into 2 - x heads when [0, 1] are turned over (2 vs. 2 when x = 0, 1 vs. 1 when x = 1, and 0 vs. 0 when x = 2).
Example 2
Input: n = 8, h = 3
Output: {"pile1": [0, 1, 2], "pile2": [3, 4, 5, 6, 7], "flip": [0, 1, 2]}
Explanation: Although h = 3 is odd, inverting [0, 1, 2] changes the total number of heads so both groups finish with 3 - x heads whenever x initial heads start in "pile1".
Example 3
Input: n = 4, h = 0
Output: {"pile1": [], "pile2": [0, 1, 2, 3], "flip": []}
Explanation: No coins show heads initially, so leaving "pile1" empty and "pile2" unflipped leaves 0 heads in each group.
Example 4
Input: n = 3, h = 3
Output: {"pile1": [0, 1, 2], "pile2": [], "flip": [0, 1, 2]}
Explanation: Every coin starts as heads. Placing all 3 indices into "pile1" and inverting them turns all 3 to tails, leaving 0 heads in both "pile1" and the empty "pile2".
Constraints
0 <= n <= 10^50 <= h <= n(inputs withn < 0,h < 0, orh > nmust raiseValueError)- Expected time and auxiliary output space:
O(n)
Step-by-step walkthrough
Understand the blindfold rules and output format
Imagine sitting in a dark room in front of
ncoins numbered0, 1, ..., n - 1. You are told that exactlyhcoins are currently heads-up, and the remainingn - hcoins are tails-up — but you have no idea which coins are which.Without looking at any coin, you must divide all
ncoins into two piles (they do not have to contain the same number of coins!) and choose any subset of coins to flip over, so that both piles end up with the exact same number of heads for every possible starting placement of thehheads.Following the canonical output format,
split_coins_to_match_heads(n, h)returns a dictionary with three sorted lists of coin indices:"pile1": coin indices placed into the first pile,"pile2": coin indices placed into the second pile,"flip": coin indices that get turned over (H -> TandT -> H).
Why splitting in half or skipping flips fails
Before looking for the trick, check why intuitive ideas break down:
- Splitting into two equal halves without flipping fails: Suppose
n = 4andh = 2. If you put[0, 1]in Pile 1 and[2, 3]in Pile 2 without flipping, what if the two heads happen to be coins0and1? Pile 1 has2heads and Pile 2 has0heads. A valid plan must work 100% of the time, not just on average. - Odd
hmakes zero-flip plans obviously impossible: Supposen = 8andh = 3(Example 2). If you never invert a coin, there are3heads in total, and3cannot be divided into two equal integers! Inverting coins changes the total head count, which is what makes oddhsolvable.
- Splitting into two equal halves without flipping fails: Suppose
Discover the strategy instead of guessing it
How could someone derive this puzzle's answer from scratch instead of waiting for a flash of inspiration? Use one line of algebra!
Suppose we try the simplest possible family of plans: put
kcoins into Pile 1 and flip allkof them, while leaving the remainingn - kcoins untouched in Pile 2.Let
xbe the unknown number of heads that happened to land inside Pile 1 before any flips:- Because there were
hheads on the whole table andxof them went into Pile 1, the untouched Pile 2 holdsh - xheads. - Pile 1 holds
kcoins in total:xheads andk - xtails. When we flip every coin in Pile 1, itsxheads become tails and itsk - xtails become heads, so Pile 1 ends up withk - xheads.
Now compare the final head counts of the two piles:
Final heads in Pile 1 = k - x Final heads in Pile 2 = h - xLook at those two expressions! How can we make
k - xequalh - xwithout knowingx?Choose
k = h! Then both expressions becomeh - x, and the unknownxcancels out completely! In math and computer science, this guaranteed equality across all hidden cases is called an invariant (a relationship that remains true no matter which hidden state occurs).- Because there were
Watch `x` cancel out on concrete examples
Let's trace Example 1 (
n = 5, h = 2) withpile1 = [0, 1],pile2 = [2, 3, 4], andflip = [0, 1]across every possible number of headsxthat could start in Pile 1:Setup: n = 5 coins, h = 2 heads total. Plan: Pile 1 gets 2 coins [0, 1] (FLIP ALL), Pile 2 gets 3 coins [2, 3, 4] (NO FLIP). Case x = 0 (example: T T | H H T) Before flip: Pile 1 = [T, T] (0 heads, 2 tails) | Pile 2 = [H, H, T] (2 heads) After flip: Pile 1 = [H, H] (2 heads) | Pile 2 = [H, H, T] (2 heads) -> 2 == 2! Case x = 1 (example: H T | T H T) Before flip: Pile 1 = [H, T] (1 head, 1 tail) | Pile 2 = [T, H, T] (1 head) After flip: Pile 1 = [T, H] (1 head) | Pile 2 = [T, H, T] (1 head) -> 1 == 1! Case x = 2 (example: H H | T T T) Before flip: Pile 1 = [H, H] (2 heads, 0 tails) | Pile 2 = [T, T, T] (0 heads) After flip: Pile 1 = [T, T] (0 heads) | Pile 2 = [T, T, T] (0 heads) -> 0 == 0!Also check the remaining statement examples:
- Example 2 (
n = 8, h = 3): Pile 1 gets[0, 1, 2](inverted) and Pile 2 gets[3..7]. If1head started in Pile 1 (x = 1), inverting Pile 1 turns[1 head, 2 tails]into2heads, matching the3 - 1 = 2heads in Pile 2! - Example 3 (
n = 4, h = 0): Pile 1 is[],flipis[], and Pile 2 is[0, 1, 2, 3](0heads vs.0heads). - Example 4 (
n = 3, h = 3): Pile 1 is[0, 1, 2],flipis[0, 1, 2](all3heads invert to0heads), and Pile 2 is[](0heads vs.0heads).
- Example 2 (
Write the Python plan
Any subset of
hcoins would work on a physical table, and our canonical output format chooses the firsthcoins0 .. h - 1for"pile1", the remainingn - hcoinsh .. n - 1for"pile2", and a fresh list copylist(pile1)for"flip". We also check0 <= h <= n(withn >= 0) so impossible inputs raiseValueError.from typing import Dict, List def split_coins_to_match_heads(n: int, h: int) -> Dict[str, List[int]]: if n < 0 or h < 0 or h > n: raise ValueError("need 0 <= h <= n") pile1: List[int] = list(range(h)) pile2: List[int] = list(range(h, n)) flip: List[int] = list(pile1) return {"pile1": pile1, "pile2": pile2, "flip": flip}Complete solution
Here is the complete solution with full type imports and explanatory comments:
from typing import Any, Dict, List, Optional, Set, Tuple def split_coins_to_match_heads(n: int, h: int) -> Dict[str, List[int]]: """Return a blind split-and-flip plan that leaves both piles with equal heads.""" # Phase 1: Validate that n is non-negative and the head count h fits inside n coins. if n < 0 or h < 0 or h > n: raise ValueError("need 0 <= h <= n") # Phase 2: Partition coins 0..n-1 into a first pile of size h and a second pile of size n - h. # pile1: coin indices [0, 1, ..., h - 1] (empty list [] when h == 0). pile1: List[int] = list(range(h)) # pile2: remaining coin indices [h, h + 1, ..., n - 1], left completely untouched. pile2: List[int] = list(range(h, n)) # Phase 3: Flip every coin in pile1 (make a separate list copy so callers cannot alias pile1). # If x hidden heads landed in pile1, pile1 starts with h - x tails and flips to h - x heads, # matching the h - x untouched heads sitting in pile2 for every possible x in 0..h. flip: List[int] = list(pile1) return {"pile1": pile1, "pile2": pile2, "flip": flip}✅ Submit now — all tests should pass.
Intuition & how it works
Picture yourself blindfolded at a table with n coins where exactly h coins are heads-up at unknown positions. If you count off any h coins into Pile 1 and leave the remaining n - h coins in Pile 2, let x be the unknown number of heads that landed in Pile 1. Then Pile 2 automatically holds the remaining h - x heads, and Pile 1 — because its total size was chosen to be h — holds x heads and h - x tails. Flipping every single coin in Pile 1 turns those h - x tails into h - x heads, creating an invariant (a mathematical relationship that stays true across every possible hidden case): both piles end with h - x heads, no matter what x was!
Naive attempts fail because they assume the piles must be equal in total size (n / 2 each) or forget to use flips to cancel the unknown x. Splitting n coins in half without flipping works only on average and fails whenever heads cluster on one side, and when h is odd (such as h = 3), equal head counts are impossible without flipping coins to change the total number of heads.
Trace Example 1 (n = 5, h = 2, giving pile1 = [0, 1], pile2 = [2, 3, 4], flip = [0, 1]):
- If
0heads landed in Pile 1 ([T, T]vs.[H, H, T]): flipping Pile 1 gives[H, H], so both piles have2heads. - If
1head landed in Pile 1 ([H, T]vs.[T, H, T]): flipping Pile 1 gives[T, H], so both piles have1head. - If
2heads landed in Pile 1 ([H, H]vs.[T, T, T]): flipping Pile 1 gives[T, T], so both piles have0heads.
Complexity
- Time:
O(n), because we constructpile1(hintegers),pile2(n - hintegers), andflip(hintegers) in a single linear pass ofn + h <= 2nlist elements. - Space:
O(n)to store and return the three output lists of coin indices (on a physical tabletop, executing the strategy usesO(1)memory: you simply count up tohand flip each coin as you move it).
Edge cases
- No heads (
h = 0):pile1andflipare both empty[], andpile2holds allntails-up coins (0heads vs.0heads). - All heads (
h = n):pile1holds allncoins andflipturns allnheads into tails, whilepile2is empty[](0heads vs.0heads). - Empty table (
n = 0, h = 0): All three lists are[], with0heads in each pile. - Odd
h(e.g.,n = 8, h = 3): Works without any special case because inverting Pile 1 changes the total head count fromh(3) to2 * (h - x)(6,4,2, or0), which is always even! - Invalid counts (
h < 0,h > n, orn < 0): Cannot represent a valid tabletop ofncoins withhheads, so raisingValueErrorsurfaces the bad input immediately.
Common mistakes
- Assuming the two piles must have equal coin counts (
n / 2): Nothing in the problem requires equal total coins — only equal heads. Pile 1 hashcoins and Pile 2 hasn - hcoins (one pile can even have0coins whenh = 0orh = n). - Flipping the
n - hpile instead of thehpile: If Pile 1 hashcoins (xheads) and you flip Pile 2 (n - hcoins,h - xheads) instead, Pile 2 ends with(n - h) - (h - x) = n - 2h + xheads, which does not equalxunlessn = 2h. - Aliasing
flip = pile1directly: Returning the exact same list object under two keys means a caller mutatingresult["flip"]silently mutatesresult["pile1"];flip = list(pile1)avoids that bug cleanly. - Giving the procedure in an interview without the
h - xproof: Saying "takehcoins and flip them" takes five seconds; interviewers ask this question specifically to hear the clear two-line algebraic cancellation (xheads in Pile 1 ->h - xtails ->h - xheads after flipping =h - xheads in Pile 2).
Follow-up questions
- Is isolating h coins and inverting all of them the unique deterministic blind plan that works for every arrangement? For
0 < h < n, yes — up to swapping the labels of Pile 1 and Pile 2 and choosing whichhindices enter the inverted pile! Considerdiff = (heads in Pile 1) - (heads in Pile 2)after flips: an initial head placed unflipped into Pile 1 (or flipped into Pile 2) contributes+1relative to a tail at that index, whereas an initial head placed flipped into Pile 1 (or unflipped into Pile 2) contributes-1. If both coin roles existed simultaneously, shifting one hidden head from a+1slot to a-1slot would alterdiffby2, breaking equality — so allncoins must share one role, meaning one pile is 100% flipped, the other is 0% flipped, anddiff == 0forces the flipped pile to holdhcoins. - Could a deterministic blind strategy still succeed if the initial head count h were unknown? No deterministic blind plan can work across all initial head counts. Take any fixed partition-and-flip plan and any starting configuration where it achieves
left_heads == right_heads, then secretly turn a single coin over before the plan runs: that coin's final face reverses inside whichever single pile holds it, shifting that pile's head count by±1while leaving the other pile unchanged, so no single plan can succeed for bothhandh + 1initial heads. - How does the strategy adapt if both piles must finish with the same number of tails instead of heads? Apply the same cancellation symmetry to tails: knowing
hcoins start as heads tells yout = n - hcoins start as tails. Placen - hcoins into Pile 1 and invert all of them; ifyinitial tails landed in Pile 1, inverting turns its(n - h) - yheads into(n - h) - ytails, matching the(n - h) - yuntouched tails left in Pile 2.
Follow-up questions
- Is isolating h coins and inverting all of them the unique deterministic blind plan that works for every arrangement?
- Could a deterministic blind strategy still succeed if the initial head count h were unknown?
- How does the strategy adapt if both piles must finish with the same number of tails instead of heads?
Similar questions
- Black-Scholes Option Delta and Hedging
- Expected Flips Until a Target Coin Sequence
- OLS Linear Regression Conditions, Diagnostics, and Remedies
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination