← Questions

Winner of a stack-merging game

0
GoogleCodingLast asked Jan 2026

A coding interview question asked in Google's first round (coding), last asked Jan 2026. It tests game theory, recursion and memoization.

Two players play a game on a row of stacks of coins. On a turn, a player picks two adjacent stacks whose combined size is at most limit and merges them into one stack in the same place. Players alternate, and a player who cannot move loses. Given the starting stacks and the limit, decide whether the first player wins when both play optimally.

Interface

Unless you agree on different rules or interface with the interviewer, assume:

  • first_player_wins(stacks: list[int], limit: int) -> bool

Example

stacks = [1, 1, 1],    limit = 2   ->  True    # merge to [2, 1]; no move is left
stacks = [1, 1, 1],    limit = 3   ->  False   # any move gives [2, 1] or [1, 2]; the opponent merges to [3]
stacks = [1, 1, 1, 1], limit = 2   ->  True    # merge the middle pair: [1, 2, 1] has no move
stacks = [2, 2],       limit = 3   ->  False   # no move at all

Constraints

  • Up to about 15 stacks with small sizes, so the state space is searchable with memoization.
  • Sizes and limit are positive integers.

Clarifying questions

  • Which stacks may be merged: adjacent ones only, or any two? Is there a size limit?
  • Does the player who makes the last move win (normal play)?
  • How many stacks and how large, so I know how big the state space is?

What a strong answer covers

  • The game is impartial with finite play (each move removes a stack), so every position is a win or a loss: a position is winning if some move leads to a losing position.
  • Recursive search over states encoded as tuples, with memoization; an estimate of the number of reachable states.
  • Simplifications: with no limit the game always lasts exactly n - 1 moves, so parity decides it.
  • Canonical forms to shrink the state space (a reversed row is equivalent), and Sprague-Grundy values if the row splits into independent parts.
  • Tests from hand-worked small positions, like the ones above.

Follow-ups

  • Any two stacks may be merged, not only neighbours.
  • Return a winning move, not only who wins.
  • The last player to move loses (misère play).

Where it's asked

  • Google · First round: coding · Last asked Jan 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI

What it tests

game theory · recursion · memoization

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding