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:

  1. A lightweight rule that locks in a guaranteed lower bound on Player A's final total regardless of how Player B responds.
  2. 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

  1. Frame the game, required information, and what "optimal" means

    Index the row of coins from 0 to n - 1 as c[0], c[1], ..., c[n - 1], where n = 2m is even, and let T = 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 scores score_A and score_B always satisfy score_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). Subtracting score_B = T - score_A gives:

    net lead = score_A - score_B = 2 * score_A - T
    score_A  = (T + net_lead) / 2
    score_B  = (T - net_lead) / 2
    

    Because T is 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 (> 0 strict win, = 0 tie, < 0 loss).

    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).
    
  2. 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 0 or from 1 creates the exact same two alternating groups of m coins):

    • 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, so l and r have opposite parity (one E, one O). 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 m coins of the chosen group, scoring exact max(S_even, S_odd) >= T / 2 regardless 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 = 12
      • S_odd = c[1] + c[3] = 3 + 10 = 13
      • Picking O (S_odd = 13), A takes 10 (c[3]) on Turn 1 and is guaranteed 13 vs. 12 (a +1 lead).
  3. 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 of coins = [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 5 instead of 7 on Turn 2? Then A would face [3, 7], grab 7, and score 10 + 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 (15 vs. 10 here, and 17 vs. 8 if B slips up).

  4. 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 on c[i..j]: - Base case (i == j, one coin left): The mover takes c[i] and the subgame ends, so f[i][i] = c[i]. - Choice on c[i..j] (i < j): - If the mover takes the left coin c[i], they immediately gain +c[i], and then the opponent becomes the mover on c[i + 1 .. j] and forces a net lead of f[i + 1][j] against the first mover — leaving a net lead of c[i] - f[i + 1][j]. - Symmetrically, taking the right coin c[j] leaves a net lead of c[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 == 10
    

    Trace the full table f[i][j] on coins = [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                      10
    

    Computing the full n × n table takes O(n²) time and O(n²) space (keeping the full table lets A look up the optimal move c[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 value f[0][n - 1], one rolling 1D array of size n cuts space to O(n)). Because the parity strategy is always one legal way for A to play, (T + f[0][n - 1]) / 2 is always >= max(S_even, S_odd).

  5. 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_odd is a sufficient condition for a strict first-player win, not a necessary one: when S_even == S_odd, you must check whether f[0][n - 1] > 0 (strict win) or f[0][n - 1] == 0 (forced tie).

  6. Put the complete interview answer together

    1. Game model & required info: Because score_A + score_B = T is constant, maximizing A's score equals maximizing A's net lead score_A - score_B under minimax play. The parity bound needs only which alternating sum (S_even vs. S_odd) is bigger and coin index parities; true optimal play requires all exact values c[0..n - 1] up front.
    2. Guaranteed lower-bound strategy (O(n) time, O(1) extra space): Compare S_even and S_odd and 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 guarantees max(S_even, S_odd) >= T / 2 against any opponent.
    3. True optimal strategy (O(n²) DP): Compute f[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, 15 vs. parity's 13 on [5, 3, 7, 10]).
    4. 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 whenever S_even != S_odd, and when S_even == S_odd it holds if and only if f[0][n - 1] > 0 (as in [2, 1, 2, 3], where A wins 5 to 3).

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 = T is 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) splits c[0..n - 1] into S_even and S_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 to max(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 slices c[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, yielding score_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, 3 to 3). S_even != S_odd guarantees a strict win, while S_even == S_odd can still be either a forced tie ([1, 2, 2, 1]) or a strict win ([2, 1, 2, 3], where f[0][3] = 2 and A wins 5 to 3).

Common mistakes

  • Playing greedy (max(left, right)). Greedy ignores what coin it uncovers for B next turn; on [8, 15, 3, 7], taking 8 exposes 15 and loses 15 to 18, whereas taking 7 wins 22 to 11.
  • Equating the parity strategy with the minimax-optimal strategy. Parity guarantees a non-losing floor (13 on [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]). On c[i + 1 .. j], it is the opponent's turn to move, so the opponent's forced lead f[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] is score_A - score_B; convert back via score_A = (T + f[0][n - 1]) / 2.
  • Trying to use the parity trick when n is odd. On an odd row like [1, 5, 1], both ends share the same parity (index 0 and index 2), so A takes a 1, exposes 5 to B, and loses 2 to 5.

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 score max(S_even, S_odd) > T / 2 (though the exact optimal winning margin still requires the DP, since f[0][n - 1] can exceed |S_even - S_odd|, as in [5, 3, 7, 10] where lead 5 > 1). When S_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 get f[0][3] = 0 (forced 3–3 tie), whereas on [2, 1, 2, 3] we get f[0][3] = 2 (A takes 3, B must take one 2 from [2, 1, 2], and A takes the other 2 to win 5–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 (0 and n - 1) have even index parity, meaning A can lose even with optimal play (for example, on [1, 100, 1], A must take 1 and B wins 100 to 2). Remarkably, the exact same interval DP formula f[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 = -98 on [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]) / 2 and opening move, each slice length depends only on slices of length - 1, so a single 1D array dp of size n updated in place computes f[0][n - 1] in O(n²) time and O(n) space. However, if A is playing interactively turn-by-turn against a live opponent who might make sub-optimal moves, keeping the O(n²) table lets A immediately look up the best move in O(1) time at every subsequent state (i, j) rather than recomputing from scratch each turn.

Follow-up questions

Similar questions

More Tekion interview questions

All 4 Tekion questions →