Heavy-Ball Weighing and Bridge Crossing Puzzles
Medium · Statistics & Math · Software Engineer · Onsite
Prompt
Solve both logic and optimization problems below, providing an explicit strategy alongside a rigorous proof of optimality for each:
- Finding the heavier ball: Out of 12 balls that look completely alike, 11 have identical mass and 1 is strictly heavier. Your only instrument is an unmarked two-pan balance scale. Give a step-by-step plan that always identifies the heavy ball within 3 scale comparisons, and prove why 3 comparisons are both sufficient and strictly required in the worst case.
- Nighttime footbridge schedule: Four hikers stand on the near bank of a narrow footbridge after dark with a single lantern. Their individual one-way walking durations are
1,2,7, and10minutes. No more than two hikers may step onto the bridge simultaneously (traveling together at the slower hiker's pace), and every trip in either direction must carry the lantern. Determine the smallest possible total elapsed time for all four hikers to reach the far bank, list the exact sequence of crossings, and prove that no valid schedule finishes in fewer minutes.
Scope & Expectations
- Paired upper and lower bounds: Each problem requires both an explicit constructive method achieving the claimed optimum and a formal proof ruling out any better worst-case bound.
- Ternary outcome analysis (Problem 1): Complete decision tree for all outcomes across up to 3 balance comparisons, paired with an outcome-counting argument showing why 2 comparisons cannot separate all 12 candidates.
- Relay scheduling & exhaustive proof (Problem 2): Exact trip-by-trip timeline reaching the minimum crossing time, backed by a case-by-case lower bound over all legal forward and return crossings.
Step-by-step walkthrough
How to prove an optimum: upper bound plus lower bound
Both puzzles ask you to find a minimum (3 weighings, 17 minutes) and justify/prove that nothing smaller works. Every complete optimality answer has two distinct halves:
1. Sufficiency (Upper Bound): Give an explicit strategy that ALWAYS finishes in <= K. 2. Necessity (Lower Bound): Prove NO legal strategy can guarantee < K in all cases.Candidates often give the right procedure and stop—earning only half credit. Below we build both halves for each puzzle with zero hand-waving.
Puzzle 1 (12 balls): prove 2 weighings are impossible (necessity)
Every time you use a two-pan balance scale, you observe one of 3 possible outcomes: 1. The left pan sinks (left side is heavier), 2. The right pan sinks (right side is heavier), or 3. The scale stays level (both pans weigh the same).
Even when your choice for Weighing 2 adapts to what happened in Weighing 1, any strategy forms a ternary decision tree (a branching tree where each test splits into at most 3 branches):
Number of weighings (w) Maximum distinct outcome histories (3^w) ----------------------- ---------------------------------------- 1 3 2 3 * 3 = 9 3 3 * 3 * 3 = 27Suppose the heavy ball exceeds a normal ball by a tiny unknown amount
delta > 0(say0.001g, smaller than one ball's weight). Notice first that putting unequal counts of balls on the two pans (say 3 balls vs. 2 balls) makes the 3-ball pan sink no matter where the heavy ball is—giving only 1 outcome and zero information! With equal counts on both pans, whichever of the 12 balls is heavy uniquely determines the exact sequence of scale outcomes.After 2 weighings, there are 12 possible heavy balls mapped into at most 9 outcome sequences. By the pigeonhole principle (if you place more items than boxes, at least one box must hold two or more items), at least two different balls produce the exact same 2-weighing outcome sequence. Because the observer sees identical scale readings for both balls, no strategy can guarantee telling them apart in 2 weighings. Therefore, at least 3 weighings are necessary.
Puzzle 1 (12 balls): find the heavy ball in 3 weighings (sufficiency)
To squeeze maximum information from a 3-outcome scale, split the remaining suspects into three nearly equal groups—left pan, right pan, and table—so every outcome eliminates roughly two-thirds of the candidates:
Start: 12 suspects {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} | +-- Weighing 1: {1, 2, 3, 4} vs {5, 6, 7, 8} (leave {9, 10, 11, 12} on table) |-- Left sinks -> heavy ball is in {1, 2, 3, 4} |-- Right sinks -> heavy ball is in {5, 6, 7, 8} +-- Level -> heavy ball is in {9, 10, 11, 12} | v Now 4 suspects remain; call them A, B, C, D. | +-- Weighing 2: {A} vs {B} (leave {C, D} on table) |-- Left sinks -> A is heavy! (solved in 2 weighings) |-- Right sinks -> B is heavy! (solved in 2 weighings) +-- Level -> heavy ball is in {C, D} | +-- Weighing 3: {C} vs {D} |-- Left sinks -> C is heavy! +-- Right sinks -> D is heavy!Every branch pinpoints the exact heavy ball in at most 3 weighings, proving 3 weighings are sufficient. Combined with our lower bound (
> 2), 3 is the exact minimum. (Note: any first weighing ofkvs.kwith2 <= k <= 6also works becausemax(k, 12 - 2k) <= 9 = 3^2, whereas1vs.1fails because a tie leaves10 > 9suspects.)def weigh_pans(left_pan: list, right_pan: list, heavy_ball: int) -> str: """Simulate a balance scale when `heavy_ball` is the single heavier ball.""" assert len(left_pan) == len(right_pan) if heavy_ball in left_pan: return "left" if heavy_ball in right_pan: return "right" return "level" def find_heavy_ball(heavy_ball: int) -> tuple: """Return (identified_ball, weighings_used) using the 3-weighing ternary split.""" w1 = weigh_pans([1, 2, 3, 4], [5, 6, 7, 8], heavy_ball) if w1 == "left": suspects = [1, 2, 3, 4] elif w1 == "right": suspects = [5, 6, 7, 8] else: suspects = [9, 10, 11, 12] a, b, c, d = suspects w2 = weigh_pans([a], [b], heavy_ball) if w2 == "left": return a, 2 if w2 == "right": return b, 2 w3 = weigh_pans([c], [d], heavy_ball) return (c, 3) if w3 == "left" else (d, 3) for actual_heavy in range(1, 13): found, count = find_heavy_ball(actual_heavy) assert found == actual_heavy and count <= 3Puzzle 2 (bridge & lantern): why pairing the slowest beats escorting
Label the four crossing times
a = 1,b = 2,c = 7, andd = 10minutes. Two hikers crossing together walk at the slower hiker's speed, and someone must carry the single lantern back after every forward crossing except the last.The obvious greedy idea—having the fastest runner (
1) escort everyone across one by one—falls into a trap because7and10pay for two separate slow trips (7 + 10 = 17before any returns!):Schedule A: Fastest escorts everyone (21 minutes) Trip 1 (fwd): 1 & 2 cross -> 2 min Trip 2 (ret): 1 returns -> 1 min Trip 3 (fwd): 1 & 7 cross -> 7 min <- pays 7 here... Trip 4 (ret): 1 returns -> 1 min Trip 5 (fwd): 1 & 10 cross -> 10 min <- ...AND 10 here! Total = 2 + 1 + 7 + 1 + 10 = 21 minutes (2a + b + c + d)To hide the
7-minute penalty inside the10-minute crossing,7and10must cross together. If7and10cross together without having to carry the lantern back themselves, a fast runner (2) must already be waiting on the far bank to ferry the lantern back! Stationing2on the far bank first gives the 17-minute relay schedule:Schedule B: Pair the two slowest via a fast relay (17 minutes) Near bank Bridge action Far bank Time ---------------- ---------------------- ---------------- ------ {1, 2, 7, 10} * 1 & 2 cross forward -> {1, 2} * 2 min {1, 7, 10} * <- 1 returns with lantern {2} 1 min {1} 7 & 10 cross forward -> {2, 7, 10} * 10 min {1, 2} * <- 2 returns with lantern {7, 10} 2 min {} 1 & 2 cross forward -> {1, 2, 7, 10} * 2 min Total = 17 minutes (a + 3b + d)(Swapping the two return runners—
2returns on Trip 2 and1returns on Trip 4—also gives2 + 2 + 10 + 1 + 2 = 17minutes.) Algebraically, Schedule B tradesc + a = 7 + 1 = 8minutes for2b = 2 + 2 = 4minutes, saving4minutes because2b < a + c.Puzzle 2 (bridge & lantern): prove no schedule takes under 17 minutes
To prove optimality, we must rule out every possible legal sequence—including schedules with solo forward trips or more than 5 crossings.
Fact 1 (at least 3 forward trips and 2 returns): Every valid schedule alternates
kforward trips (near -> far) withk - 1return trips (far -> near). Each forward trip moves at most+2hikers across; each return moves at least-1hiker back. Reaching+4hikers on the far bank requires:4 <= 2k - 1*(k - 1) = k + 1 ==> k >= 3 (at least 3 forward trips and 2 returns)Now partition all valid schedules into three exhaustive cases:
- Case 1 (
7and10never share a forward trip): One forward trip includes10(cost>= 10), a different forward trip includes7(cost>= 7), at least one more forward trip exists by Fact 1 (cost>= 1), and at least two return trips exist (cost>= 1 + 1 = 2). Total time>= 10 + 7 + 1 + 2 = 20 > 17minutes. - Case 2 (
7and10cross together on some forward tripT, and7or10makes a return trip): TripTcosts10, that slow hiker's return costs>= 7, and after returning to the near bank they must cross forward a second time (cost>= 7). Total time>= 10 + 7 + 7 = 24 > 17minutes. - Case 3 (
7and10cross together on tripTof cost10, and ONLY1and2ever return): Trace the timeline before and afterT:- Why a return happens after
T:Tcannot be the final trip, because the return trip right before the final trip puts1or2on the near bank, so ending withT = {7, 10}would leave that fast hiker stranded on the near bank. Thus someone from{1, 2}must return afterT. - Before
T: For one fast runner (yfrom{1, 2}) to already be waiting on the far bank duringTwhile the lantern is back on the near bank for{7, 10}, the other fast runner (xfrom{1, 2}) must have brought the lantern back beforeT. Because solo forward trips followed by returns leave zero net hikers behind (+1 - 1 = 0), stationingyon the far bank requires an earlier forward trip carrying both1and2together (cost2), followed byx's return (costx). - Right after
T: Since{1, 2}has only two hikers andxsat on the near bank while{7, 10}crossed onT,yis the only fast hiker on the far bank afterT—soymust make the next return trip (costy). Because{x, y} = {1, 2}, those two returns together costx + y = 1 + 2 = 3. - Finishing after
yreturns: Both1and2are now on the near bank, so2must still cross forward at least once more afterT(cost>= 2).
- Why a return happens after
Adding those five chronological, non-overlapping trips gives a hard floor:
Total time >= 2 (early 1&2 fwd) + 3 (returns by x and y) + 10 (7&10 fwd) + 2 (late fwd with 2) = 17 minutes.Every case requires
>= 17minutes and Schedule B achieves17, proving 17 minutes is strictly optimal.- Case 1 (
Exhaustive state-space verification in Python
Because there are only 4 hikers (each near or far) plus 1 lantern (near or far), the entire puzzle has just
2^4 * 2 = 32states! We can double-check our paper proof by running Dijkstra's algorithm (a graph search that always expands the lowest-elapsed-time state first, guaranteeing the shortest path when edge costs are non-negative) over all 32 states:import heapq from itertools import combinations def min_bridge_time(times: list) -> int: """Return the exact minimum crossing time across all possible schedules via Dijkstra.""" all_hikers = frozenset(range(len(times))) # State: (frozenset of hikers still on near bank, is_lantern_on_near_bank) start_state = (all_hikers, True) best_time = {start_state: 0} # Min-heap of (elapsed_minutes, tie_breaker, state) heap = [(0, 0, start_state)] tie_id = 1 while heap: elapsed, _, (near_bank, lantern_near) = heapq.heappop(heap) if elapsed > best_time[(near_bank, lantern_near)]: continue if not near_bank and not lantern_near: return elapsed active_bank = near_bank if lantern_near else (all_hikers - near_bank) # Try every 1-hiker and 2-hiker crossing from the bank holding the lantern. candidate_groups = [(p,) for p in active_bank] + list(combinations(active_bank, 2)) for group in candidate_groups: group_set = frozenset(group) next_near = (near_bank - group_set) if lantern_near else (near_bank | group_set) next_state = (next_near, not lantern_near) next_time = elapsed + max(times[p] for p in group) if next_time < best_time.get(next_state, float("inf")): best_time[next_state] = next_time heapq.heappush(heap, (next_time, tie_id, next_state)) tie_id += 1 raise ValueError("unreachable") assert min_bridge_time([1, 2, 7, 10]) == 17
Intuition & how it works
Each puzzle hinges on one clean mental shift:
- 12 balls on a balance scale: think of the game "20 Questions," except a two-pan balance scale gives 3-way answers (left heavier, right heavier, or tied) instead of 2-way Yes/No answers. Keeping one-third of the suspects off the scale turns a tie into just as sharp a clue as a tilt, dividing suspects by 3 on every comparison (12 -> 4 -> 2 -> 1).
- Footbridge and lantern (1, 2, 7, 10 minutes): think of carpooling the two slowest hikers (7 and 10) in a single slow trip so the 7-minute penalty rides for free inside the 10-minute crossing, while using the two fast hikers (1 and 2) as a two-person relay stationed on opposite sides of the bridge so neither slow hiker ever has to carry the lantern back.
The naive approach fails on both puzzles for clear reasons. On the scale, comparing 6 against 6 wastes the "level" outcome on round 1 (though 6 -> 2 -> 1 still barely fits 12, it breaks at 13, whereas 3-way splitting handles up to 27 balls!), and giving only a 3-weighing recipe without an information-theoretic lower bound (counting possible outcome histories) never proves 2 comparisons are impossible. On the bridge, greedily having the 1-minute hiker escort everyone one by one pays 7 minutes and 10 minutes on separate crossings (2 + 1 + 7 + 1 + 10 = 21 minutes), losing 4 full minutes compared with pairing 7 and 10.
Walk through a concrete mini-trace of each solution:
1. 12 balls (suppose ball #11 is heavy): Comparison 1 checks {1,2,3,4} vs. {5,6,7,8} -> level, isolating {9,10,11,12}. Comparison 2 checks {9} vs. {10} -> level, isolating {11,12}. Comparison 3 checks {11} vs. {12} -> left sinks, identifying #11 in 3 steps. Meanwhile, 2 comparisons produce at most 3 * 3 = 9 outcome sequences—fewer than 12 balls—so at least two balls must collide on the same outcome history (pigeonhole principle, which says 12 items placed into 9 boxes force a shared box).
2. Bridge (1, 2, 7, 10): 1 & 2 cross (2 min) -> 1 returns (1 min, leaving 2 waiting on the far bank) -> 7 & 10 cross together (10 min) -> 2 returns (2 min) -> 1 & 2 cross (2 min), totaling 2 + 1 + 10 + 2 + 2 = 17 minutes.
Key points
- Problem 1 answer (
3comparisons): Necessary because each comparison has3outcomes (3² = 9 < 12, so2comparisons cannot distinguish all12balls in the worst case); sufficient via4 vs. 4(leaving4suspects),1 vs. 1among those4, and1 vs. 1on the remaining2if tied. - Outcome-counting generality: the
3^wupper limit on distinguishable balls holds for every deterministic strategy, even adaptive ones where later choices depend on earlier results;wcomparisons solve up to3^wballs when one ball is known to be heavier. - Problem 2 answer (
17minutes): sequence1+2forward (2),1back (1),7+10forward (10),2back (2),1+2forward (2), with2returning first and1returning second equally achieving17. - Bridge optimality proof: any schedule needs
>= 3forward trips and>= 2returns; separating7and10costs>= 10 + 7 + 1 + 2 = 20, having7or10return costs>= 10 + 7 + 7 = 24, and pairing7+10without slow returns forces an earlier1+2forward (2), one return by1and one by2(1 + 2 = 3), the7+10crossing (10), and a final forward crossing containing2(>= 2), totaling>= 17. - When pairing beats escorting: for sorted times
a <= b <= c <= d, relay-pairing (a + 3b + d) beats fastest-hiker escorting (2a + b + c + d) whenever2b < a + c, savinga + c - 2bminutes.
Common mistakes
- Giving the upper bound without proving the lower bound: showing a 3-step tree or a 17-minute schedule only proves
min <= 3andmin <= 17; you must also provemin >= 3andmin >= 17. - Claiming a balance scale only halves suspects (
2² = 4 < 12): a two-pan balance has three outcomes (left, right, level), not two, so an interviewer will immediately challenge2^wand expect3^w(3² = 9 < 12 <= 27 = 3³). - Saying 2 comparisons never find the heavy ball: in our strategy, if ball
1is heavy,1-4 vs. 5-8(left) followed by1 vs. 2(left) finds it in just 2 steps! The necessity statement is about the worst-case guarantee across all 12 balls, not lucky branches. - Assuming
4 vs. 4is the only valid first comparison for 12 balls: because 2 remaining comparisons can resolve up to3² = 9suspects, any first splitk vs. kwith2 <= k <= 6works (6 vs. 6->2 vs. 2->1 vs. 1); only1 vs. 1fails because a tie leaves10 > 9balls. - Assuming the
1-minute hiker must carry the lantern on every return: that greedy heuristic produces21minutes instead of17. - Only comparing the two textbook 5-trip schedules in the optimality proof: a rigorous proof must also rule out asymmetric schedules (like solo forward crossings or
7returning) via trip-count bounds and exhaustive case splits.
Follow-up questions
- What changes in the 12-ball problem if the odd ball could be either heavier or lighter? Now there are
12 * 2 = 24possibilities (which ball and whether it is heavy or light), which still fits inside3³ = 27—and3comparisons still suffice! Compare{1,2,3,4}vs.{5,6,7,8}: if level,{9,10,11,12}holds the odd ball while1..8are certified normal, so Round 2 compares{9,10,11}against{1,2,3}; if{1,2,3,4}sinks instead, one of1..4is heavy or one of5..8is light, and rotating balls across pans in Round 2 ({1,2,5}vs.{3,6,9}, using normal9) narrows every outcome to<= 3possibilities for Round 3. In general,wcomparisons can identify an unknown heavier-or-lighter ball (and its direction) among at most(3^w - 3) / 2balls (12forw = 3). - How do you extend the optimal bridge-crossing schedule to n hikers with sorted times t_1 <= t_2 <= ... <= t_n? Repeatedly ferry the two slowest remaining hikers (
t_{n-1}andt_n) to the far bank using whichever two-person sub-schedule is cheaper—either fastest-escorts-both (2*t_1 + t_{n-1} + t_n) or relay-pair (t_1 + 2*t_2 + t_n)—leavingt_1andt_2back on the near bank so the problem shrinks fromnhikers ton - 2hikers! Once<= 3hikers remain, finish int_1 + t_2 + t_3(for 3),t_2(for 2), ort_1(for 1). Notice that which mode wins can change mid-problem: for[1, 4, 5, 10],2*t_2 = 8 > t_1 + t_3 = 6, so escorting (21min) actually beats pairing (23min)! - For N identical-looking balls containing one heavier ball, what is the exact minimum number of balance comparisons? It is
ceil(log_3(N))—the smallest integerwsatisfying3^w >= N(with0comparisons whenN = 1). Necessity follows immediately from3^w >= Nby the pigeonhole principle, and sufficiency follows by always splitting the currentmsuspects into three groups of sizes<= ceil(m / 3)(putting two equal-sized groups on the pans and the third on the table), shrinking the suspect pool to<= 3^(w - 1)after the first comparison and continuing inductively.
Follow-up questions
- What changes in the 12-ball problem if the odd ball could be either heavier or lighter?
- How do you extend the optimal bridge-crossing schedule to n hikers with sorted times t_1 <= t_2 <= ... <= t_n?
- For N identical-looking balls containing one heavier ball, what is the exact minimum number of balance comparisons?
Similar questions
- Core Data Structures and Complexity Trade-offs
- Operating System and Networking Essentials
- Career Overview and Recent Project Deep Dive
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips