First-Player Strategy on an Even-Length Coin Line
Medium · Statistics & Math · Software Engineer · Technical Screen
Prompt
Two competitors, Player A and Player B, face a single horizontal line containing an even count of coins with known face values. Player A moves first, and turns alternate strictly until no coins remain. On each turn, the active player must pick up exactly one coin—either the leftmost coin or the rightmost coin of the remaining contiguous line—and add its value to their personal total. When the line is exhausted, whoever holds the strictly larger total wins; identical totals produce a draw.
Present and justify an optimal playing policy for Player A. Make explicit what upfront visibility into the coin sequence your analysis relies on and how you formalize optimal play against a rational adversary. Clearly separate:
- A lightweight rule that locks in a guaranteed lower bound on Player A's final total regardless of how Player B responds.
- A full lookahead policy that maximizes Player A's final total when Player B also chooses best responses at every turn.
Finally, determine whether starting with an even number of coins is sufficient on its own to guarantee a strict victory for Player A when ties are allowed. Because this is a conceptual strategy question, no fixed input list or function signature is prescribed.
Scope & Expectations
- Formalize the two-player objective (total score vs. score margin) and state the exact information assumptions behind each strategy you discuss.
- Contrast the guaranteed score floor with true best-response optimization, showing on a small concrete coin sequence how their moves and final totals can differ.
- Characterize when Player A can force a strict win versus when optimal play from both sides inevitably ends in a tie.
Step-by-step walkthrough
Frame the game, required information, and what "optimal" means
Index the row of coins from
0ton - 1asc[0], c[1], ..., c[n - 1], wheren = 2mis even, and letT = c[0] + c[1] + ... + c[n - 1]be the sum of all face values. Because every coin is eventually taken by either A or B, their final scoresscore_Aandscore_Balways satisfyscore_A + score_B = T.That makes this a constant-sum game (equivalent to a zero-sum game once we track the lead
score_A - score_B, where every point A gains is a point B loses). Subtractingscore_B = T - score_Agives:net lead = score_A - score_B = 2 * score_A - T score_A = (T + net_lead) / 2 score_B = (T - net_lead) / 2Because
Tis fixed before the first move, maximizing A's own score and maximizing A's net lead(score_A - score_B)are the exact same goal! Under standard minimax play (a game-theory rule where each player chooses the move that maximizes their worst-case result assuming the opponent also plays best moves), the game's win/tie/loss outcome is simply the sign of the best net lead A can force (> 0strict win,= 0tie,< 0loss).Notice how the information A needs differs between the two strategies we will compare:
Strategy Information required before / during play ------------------------------------------------------------------------------------------------ 1. Parity (color-locking) bound Only which alternating sum (even indices vs. odd indices) is larger, plus each remaining end's original index parity. 2. Minimax (interval DP) optimum Perfect information: the exact face value and position of every coin c[0..n-1] before move 1 (deterministic, no luck).Guarantee a non-losing lower bound with the parity (checkerboard) trick
Color the original row like a checkerboard using index parity (whether an index is even or odd — note that counting from
0or from1creates the exact same two alternating groups ofmcoins):- Even-index group (
E):S_even = c[0] + c[2] + ... + c[n - 2] - Odd-index group (
O):S_odd = c[1] + c[3] + ... + c[n - 1]
Because
S_even + S_odd = T, the larger of the two sums is always at least half the total:max(S_even, S_odd) >= T / 2. And on an even-length row, A can force B to hand over whichever entire color group A wants! Watch why this invariant (a property that stays true before every turn of A) holds:Initial row (n = 4): [ c[0] , c[1] , c[2] , c[3] ] Original parities: E O E O <- left end is E, right end is O! Suppose S_odd >= S_even, so A decides to collect ALL 'O' coins: Turn 1 (A): Ends are (0: E, 3: O). Exactly one end is O -> A takes c[3] (O). Turn 2 (B): Remaining [c[0], c[1], c[2]] has ends (0: E, 2: E). BOTH ends are E! Whether B takes left (c[0]) or right (c[2]), B is FORCED to take an E coin, exposing an O coin next to it so the two ends are once again one E and one O!On every single one of A's turns, the remaining contiguous block
c[l..r]has even length, solandrhave opposite parity (oneE, oneO). Once A removes the chosen color, the remaining odd-length block has both ends of the other color, trapping B every time!- Guarantee: A collects all
mcoins of the chosen group, scoring exactmax(S_even, S_odd) >= T / 2regardless of what B does. Therefore, A can never lose on an even row. - Worked example
coins = [5, 3, 7, 10](T = 25):S_even = c[0] + c[2] = 5 + 7 = 12S_odd = c[1] + c[3] = 3 + 10 = 13- Picking
O(S_odd = 13), A takes10(c[3]) on Turn 1 and is guaranteed13vs.12(a+1lead).
- Even-index group (
Why the parity guarantee is NOT the true optimal strategy
The parity strategy guarantees a safe floor (
max(S_even, S_odd)), yet blindly sticking to one color can leave extra points on the table! Watch Turn 3 ofcoins = [5, 3, 7, 10]:Start: [5, 3, 7, 10] (indices 0:E, 1:O, 2:E, 3:O) 1. A takes right end 10 (index 3, O). Remaining: [5, 3, 7] 2. B faces [5, 3, 7] (ends 5 and 7). Suppose B takes right end 7 (index 2, E). Remaining: [5, 3] 3. Now A faces [5, 3] (index 0:E is 5, index 1:O is 3): - Blind parity rule says "take the O coin (3)" -> A finishes with 10 + 3 = 13, B gets 7 + 5 = 12. - Smart play says "switch colors and take 5!" -> A finishes with 10 + 5 = 15, B gets 7 + 3 = 10!(What if B had taken
5instead of7on Turn 2? Then A would face[3, 7], grab7, and score10 + 7 = 17!)This neatly separates the two concepts asked in the prompt: - Lower-bound strategy (parity rule): Pre-commits to one alternating color; locks in
max(S_even, S_odd)(13) with almost zero calculation, never doing worse and never doing better. - Score-optimal strategy against an optimal opponent (minimax): Re-evaluates every sub-row dynamically so A captures strictly larger leads whenever the coin layout permits (15vs.10here, and17vs.8if B slips up).Find the exact optimal strategy with interval dynamic programming
At any point in the game, the remaining unpicked coins form one contiguous slice
c[i..j](0 <= i <= j < n). We can solve every slice from smallest to largest using interval dynamic programming (solving a problem on larger subarrays by combining stored answers from smaller subarrays inside them).Define
f[i][j]as the maximum net lead (mover's points from c[i..j] minus other player's points from c[i..j]) that the player whose turn it is can force onc[i..j]: - Base case (i == j, one coin left): The mover takesc[i]and the subgame ends, sof[i][i] = c[i]. - Choice onc[i..j](i < j): - If the mover takes the left coinc[i], they immediately gain+c[i], and then the opponent becomes the mover onc[i + 1 .. j]and forces a net lead off[i + 1][j]against the first mover — leaving a net lead ofc[i] - f[i + 1][j]. - Symmetrically, taking the right coinc[j]leaves a net lead ofc[j] - f[i][j - 1]. - An optimal mover picks whichever end gives the larger lead:f[i][j] = max(c[i] - f[i + 1][j], c[j] - f[i][j - 1])def best_lead_table(coins): """Return f where f[i][j] is the best net lead the mover can force on coins[i..j].""" n = len(coins) f = [[0] * n for _ in range(n)] # Base case: a 1-coin slice gives that coin directly to the current mover. for i in range(n): f[i][i] = coins[i] # Fill slices in increasing order of length so shorter slices are ready first. for length in range(2, n + 1): for i in range(n - length + 1): j = i + length - 1 # Subtract the opponent's best lead on the remaining slice. take_left = coins[i] - f[i + 1][j] take_right = coins[j] - f[i][j - 1] f[i][j] = max(take_left, take_right) return f f = best_lead_table([5, 3, 7, 10]) # f[0][3] == 5 -> A's optimal score is (25 + 5) // 2 == 15, B's is (25 - 5) // 2 == 10Trace the full table
f[i][j]oncoins = [5, 3, 7, 10](T = 25):j=0 j=1 j=2 j=3 i=0 5 2 5 5 <- f[0][3] = max(5 - f[1][3], 10 - f[0][2]) i=1 3 4 6 = max(5 - 6, 10 - 5) = max(-1, 5) = 5 (take right: 10) i=2 7 3 i=3 10Computing the full
n × ntable takesO(n²)time andO(n²)space (keeping the full table lets A look up the optimal movec[i] - f[i+1][j]vs.c[j] - f[i][j-1]after any reply by B, whether B plays optimally or blunders; if you only want the numeric valuef[0][n - 1], one rolling 1D array of sizencuts space toO(n)). Because the parity strategy is always one legal way for A to play,(T + f[0][n - 1]) / 2is always>= max(S_even, S_odd).Why an even coin count does not force a strict victory
No. Starting with an even count of coins guarantees only that A never loses (
score_A >= score_B, i.e.,f[0][n - 1] >= 0). When draws are permitted, a tie can be completely unavoidable! Compare three small 4-coin cases:Case 1: Unequal parity sums -> STRICT WIN GUARANTEED coins = [5, 3, 7, 10] S_even = 12, S_odd = 13 (unequal) Parity already forces >= 13 vs. 12; optimal DP forces 15 vs. 10 (lead +5 > 0). Case 2: Equal parity sums -> FORCED TIE coins = [1, 2, 2, 1] S_even = 1 + 2 = 3, S_odd = 2 + 1 = 3 (equal) A must take a 1 -> B takes 2 -> A takes 2 -> B takes 1. f[0][3] = 0: optimal play ends 3 to 3 (strict win is impossible!). Case 3: Equal parity sums -> STRICT WIN STILL POSSIBLE VIA DP! coins = [2, 1, 2, 3] S_even = 2 + 2 = 4, S_odd = 1 + 3 = 4 (equal) Parity alone only promises 4 vs. 4, YET look at A taking right end 3: Remaining row is [2, 1, 2] — both ends are 2! Whichever 2 B takes, the other 2 stays exposed for A, leaving 1 for B. f[0][3] = 2: A wins strictly, 5 to 3!So
S_even != S_oddis a sufficient condition for a strict first-player win, not a necessary one: whenS_even == S_odd, you must check whetherf[0][n - 1] > 0(strict win) orf[0][n - 1] == 0(forced tie).Put the complete interview answer together
- Game model & required info: Because
score_A + score_B = Tis constant, maximizing A's score equals maximizing A's net leadscore_A - score_Bunder minimax play. The parity bound needs only which alternating sum (S_evenvs.S_odd) is bigger and coin index parities; true optimal play requires all exact valuesc[0..n - 1]up front. - Guaranteed lower-bound strategy (
O(n)time,O(1)extra space): CompareS_evenandS_oddand always pick the end matching the larger index parity. Because an even-length slice always has one even end and one odd end, A collects that entire half and guaranteesmax(S_even, S_odd) >= T / 2against any opponent. - True optimal strategy (
O(n²)DP): Computef[i][j] = max(c[i] - f[i + 1][j], c[j] - f[i][j - 1])and pick the maximizing end each turn, achieving(T + f[0][n - 1]) / 2 >= max(S_even, S_odd)against an optimal B (for example,15vs. parity's13on[5, 3, 7, 10]). - Strict win vs. tie: An even row alone guarantees at least a tie, not a strict win (
[4, 4]and[1, 2, 2, 1]force ties). A strict win holds wheneverS_even != S_odd, and whenS_even == S_oddit holds if and only iff[0][n - 1] > 0(as in[2, 1, 2, 3], where A wins5to3).
- Game model & required info: Because
Intuition & how it works
Picture painting the row of coins in alternating checkerboard colors — Red, Blue, Red, Blue (index 0, 1, 2, 3, ...). Because there is an even number of coins, the left end is Red and the right end is Blue! If Player A starts by picking the Blue end, the remaining row now has Red on both ends, trapping Player B into taking a Red coin — which immediately uncovers another Blue coin for A. That means A can pre-select whichever color has the bigger sum and collect every single coin of that color, guaranteeing at least half the total points before the game even begins!
Two naive instincts trip people up here:
1. Naive greedy ("always grab the bigger of the two visible ends"): On [8, 15, 3, 7], grabbing 8 over 7 uncovers the huge 15 for Player B! B grabs 15, and greedy A loses 15 to 18 — even though A went first on an even row.
2. Stopping at the checkerboard trick and calling it "optimal": Sticking rigidly to one color guarantees you never lose, yet it ignores moments when switching colors mid-game wins even more points!
Watch both ideas on the tiny 4-coin row [5, 3, 7, 10] (total T = 25):
- Checkerboard guarantee: Red positions (5 + 7 = 12) vs. Blue positions (3 + 10 = 13). Locking onto Blue starts by taking 10 and guarantees A 13 vs. 12.
- True optimal play (lookahead): After A takes 10, B faces [5, 3, 7] and does best by taking 7, leaving [5, 3]. At [5, 3], the rigid Blue rule would tell A to take 3 (13 total), whereas looking ahead tells A to switch colors and take 5, finishing with 15 vs. 10! Computing the best net lead on every sub-row from shortest to longest captures that exact 15.
Key points
- Constant-sum game -> minimax on net lead. Because
score_A + score_B = Tis fixed,score_A - score_B = 2 * score_A - T. Under minimax (each player maximizing their own result assuming best replies from the opponent), maximizing A's score and maximizing A's net lead are identical. - Parity strategy =
O(n)guaranteed lower bound (>= T / 2). Index parity (even vs. odd index) splitsc[0..n - 1]intoS_evenandS_odd. Because every even-length subarray has one even-index end and one odd-index end (an invariant preserved after every pair of turns), A can collect whichever full group sums tomax(S_even, S_odd) >= T / 2, needing only which sum is larger and coin positions. - Interval DP =
O(n²)true optimal score against an optimal opponent. Using interval dynamic programming (filling answers for slicesc[i..j]by increasing length),f[i][j] = max(c[i] - f[i + 1][j], c[j] - f[i][j - 1])gives the best net lead the current mover can force, yieldingscore_A = (T + f[0][n - 1]) / 2 >= max(S_even, S_odd). This requires knowing every coin's exact value and order up front. - Even coin count guarantees "no loss," NOT a strict win. Ties are forced on symmetric rows like
[4, 4]or[1, 2, 2, 1](f[0][3] = 0,3to3).S_even != S_oddguarantees a strict win, whileS_even == S_oddcan still be either a forced tie ([1, 2, 2, 1]) or a strict win ([2, 1, 2, 3], wheref[0][3] = 2and A wins5to3).
Common mistakes
- Playing greedy (
max(left, right)). Greedy ignores what coin it uncovers for B next turn; on[8, 15, 3, 7], taking8exposes15and loses15to18, whereas taking7wins22to11. - Equating the parity strategy with the minimax-optimal strategy. Parity guarantees a non-losing floor (
13on[5, 3, 7, 10]), whereas optimal DP achieves a higher score (15) by switching parities when profitable. - Claiming an even number of coins always gives A a strict win. When ties are permitted, identical coins (
[4, 4]) or palindromes ([1, 2, 2, 1]) force a tie under optimal play. - Writing the DP recurrence without flipping turns (
c[i] + f[i + 1][j]). Onc[i + 1 .. j], it is the opponent's turn to move, so the opponent's forced leadf[i + 1][j]must be subtracted, not added. - Returning
f[0][n - 1]as A's score instead of A's lead.f[0][n - 1]isscore_A - score_B; convert back viascore_A = (T + f[0][n - 1]) / 2. - Trying to use the parity trick when
nis odd. On an odd row like[1, 5, 1], both ends share the same parity (index 0andindex 2), so A takes a1, exposes5to B, and loses2to5.
Follow-up questions
- If the two alternating index-parity groups have different total values, what outcome can Player A guarantee immediately, and why do equal parity totals leave a strict win versus a tie undecided? When
S_even != S_odd, A is guaranteed a strict win under optimal play with a lead of at least|S_even - S_odd| > 0, because A always has the option to lock onto the larger parity class and scoremax(S_even, S_odd) > T / 2(though the exact optimal winning margin still requires the DP, sincef[0][n - 1]can exceed|S_even - S_odd|, as in[5, 3, 7, 10]where lead5 > 1). WhenS_even == S_odd, the parity argument only guarantees a tie (score_A >= T / 2), leaving completely undecided whether A can actually force a strict win or is stuck in a forced tie! Only running the interval DP settles that question: on[1, 2, 2, 1]we getf[0][3] = 0(forced3–3tie), whereas on[2, 1, 2, 3]we getf[0][3] = 2(A takes3, B must take one2from[2, 1, 2], and A takes the other2to win5–3). - How do the parity guarantee and the dynamic-programming recurrence change if the initial line contains an odd number of coins? The parity guarantee disappears completely because both ends of an odd-length row (
0andn - 1) have even index parity, meaning A can lose even with optimal play (for example, on[1, 100, 1], A must take1and B wins100to2). Remarkably, the exact same interval DP formulaf[i][j] = max(c[i] - f[i + 1][j], c[j] - f[i][j - 1])still works without changing a single line of code:f[0][n - 1]simply becomes negative (1 - 99 = -98on[1, 100, 1]) whenever Player B has a forced win! - How can the dynamic-programming table be compressed to linear memory, and when would you still retain the full two-dimensional table? If we only need A's optimal final score
(T + f[0][n - 1]) / 2and opening move, each slice length depends only on slices oflength - 1, so a single 1D arraydpof sizenupdated in place computesf[0][n - 1]inO(n²)time andO(n)space. However, if A is playing interactively turn-by-turn against a live opponent who might make sub-optimal moves, keeping theO(n²)table lets A immediately look up the best move inO(1)time at every subsequent state(i, j)rather than recomputing from scratch each turn.
Follow-up questions
- If the two alternating index-parity groups have different total values, what outcome can Player A guarantee immediately, and why do equal parity totals leave a strict win versus a tie undecided?
- How do the parity guarantee and the dynamic-programming recurrence change if the initial line contains an odd number of coins?
- How can the dynamic-programming table be compressed to linear memory, and when would you still retain the full two-dimensional table?
Similar questions
- Open Lockers After Multi-Pass Toggling
- Peak Concurrent Active Loans
- Stock Trading Profit With Bounded Trades
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips