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^5
  • 0 <= h <= n (inputs with n < 0, h < 0, or h > n must raise ValueError)
  • Expected time and auxiliary output space: O(n)

Step-by-step walkthrough

  1. Understand the blindfold rules and output format

    Imagine sitting in a dark room in front of n coins numbered 0, 1, ..., n - 1. You are told that exactly h coins are currently heads-up, and the remaining n - h coins are tails-up — but you have no idea which coins are which.

    Without looking at any coin, you must divide all n coins 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 the h heads.

    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 -> T and T -> H).
  2. 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 = 4 and h = 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 coins 0 and 1? Pile 1 has 2 heads and Pile 2 has 0 heads. A valid plan must work 100% of the time, not just on average.
    • Odd h makes zero-flip plans obviously impossible: Suppose n = 8 and h = 3 (Example 2). If you never invert a coin, there are 3 heads in total, and 3 cannot be divided into two equal integers! Inverting coins changes the total head count, which is what makes odd h solvable.
  3. 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 k coins into Pile 1 and flip all k of them, while leaving the remaining n - k coins untouched in Pile 2.

    Let x be the unknown number of heads that happened to land inside Pile 1 before any flips:

    1. Because there were h heads on the whole table and x of them went into Pile 1, the untouched Pile 2 holds h - x heads.
    2. Pile 1 holds k coins in total: x heads and k - x tails. When we flip every coin in Pile 1, its x heads become tails and its k - x tails become heads, so Pile 1 ends up with k - x heads.

    Now compare the final head counts of the two piles:

    Final heads in Pile 1  =  k - x
    Final heads in Pile 2  =  h - x
    

    Look at those two expressions! How can we make k - x equal h - x without knowing x?

    Choose k = h! Then both expressions become h - x, and the unknown x cancels 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).

  4. Watch `x` cancel out on concrete examples

    Let's trace Example 1 (n = 5, h = 2) with pile1 = [0, 1], pile2 = [2, 3, 4], and flip = [0, 1] across every possible number of heads x that 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]. If 1 head started in Pile 1 (x = 1), inverting Pile 1 turns [1 head, 2 tails] into 2 heads, matching the 3 - 1 = 2 heads in Pile 2!
    • Example 3 (n = 4, h = 0): Pile 1 is [], flip is [], and Pile 2 is [0, 1, 2, 3] (0 heads vs. 0 heads).
    • Example 4 (n = 3, h = 3): Pile 1 is [0, 1, 2], flip is [0, 1, 2] (all 3 heads invert to 0 heads), and Pile 2 is [] (0 heads vs. 0 heads).
  5. Write the Python plan

    Any subset of h coins would work on a physical table, and our canonical output format chooses the first h coins 0 .. h - 1 for "pile1", the remaining n - h coins h .. n - 1 for "pile2", and a fresh list copy list(pile1) for "flip". We also check 0 <= h <= n (with n >= 0) so impossible inputs raise ValueError.

    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}
    
  6. 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 0 heads landed in Pile 1 ([T, T] vs. [H, H, T]): flipping Pile 1 gives [H, H], so both piles have 2 heads.
  • If 1 head landed in Pile 1 ([H, T] vs. [T, H, T]): flipping Pile 1 gives [T, H], so both piles have 1 head.
  • If 2 heads landed in Pile 1 ([H, H] vs. [T, T, T]): flipping Pile 1 gives [T, T], so both piles have 0 heads.

Complexity

  • Time: O(n), because we construct pile1 (h integers), pile2 (n - h integers), and flip (h integers) in a single linear pass of n + h <= 2n list elements.
  • Space: O(n) to store and return the three output lists of coin indices (on a physical tabletop, executing the strategy uses O(1) memory: you simply count up to h and flip each coin as you move it).

Edge cases

  • No heads (h = 0): pile1 and flip are both empty [], and pile2 holds all n tails-up coins (0 heads vs. 0 heads).
  • All heads (h = n): pile1 holds all n coins and flip turns all n heads into tails, while pile2 is empty [] (0 heads vs. 0 heads).
  • Empty table (n = 0, h = 0): All three lists are [], with 0 heads 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 from h (3) to 2 * (h - x) (6, 4, 2, or 0), which is always even!
  • Invalid counts (h < 0, h > n, or n < 0): Cannot represent a valid tabletop of n coins with h heads, so raising ValueError surfaces 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 has h coins and Pile 2 has n - h coins (one pile can even have 0 coins when h = 0 or h = n).
  • Flipping the n - h pile instead of the h pile: If Pile 1 has h coins (x heads) and you flip Pile 2 (n - h coins, h - x heads) instead, Pile 2 ends with (n - h) - (h - x) = n - 2h + x heads, which does not equal x unless n = 2h.
  • Aliasing flip = pile1 directly: Returning the exact same list object under two keys means a caller mutating result["flip"] silently mutates result["pile1"]; flip = list(pile1) avoids that bug cleanly.
  • Giving the procedure in an interview without the h - x proof: Saying "take h coins and flip them" takes five seconds; interviewers ask this question specifically to hear the clear two-line algebraic cancellation (x heads in Pile 1 -> h - x tails -> h - x heads after flipping = h - x heads 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 which h indices enter the inverted pile! Consider diff = (heads in Pile 1) - (heads in Pile 2) after flips: an initial head placed unflipped into Pile 1 (or flipped into Pile 2) contributes +1 relative 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 +1 slot to a -1 slot would alter diff by 2, breaking equality — so all n coins must share one role, meaning one pile is 100% flipped, the other is 0% flipped, and diff == 0 forces the flipped pile to hold h coins.
  • 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 ±1 while leaving the other pile unchanged, so no single plan can succeed for both h and h + 1 initial 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 h coins start as heads tells you t = n - h coins start as tails. Place n - h coins into Pile 1 and invert all of them; if y initial tails landed in Pile 1, inverting turns its (n - h) - y heads into (n - h) - y tails, matching the (n - h) - y untouched tails left in Pile 2.

Follow-up questions

Similar questions

More Bnp interview questions

All 4 Bnp questions →