KatInterview

Coin Pile Fusion: Who Makes the Last Merge?

Dynamic ProgrammingAuto-graded · 22 test cases
HardAuto-gradedDynamic Programminggame-theorymemoizationbacktracking

Last updated

Decide the winner of a two-player impartial game where piles are fused under a size cap, using memoized game-tree search over canonical multiset states.

Coin Pile Fusion

Two players share a row of coin piles. The i-th pile holds piles[i] coins. The players alternate turns, and the first player moves first.

On a turn, the active player must pick two different piles with sizes a and b and fuse them into one pile of size a + b. A fusion is legal only if a + b <= limit. The two original piles are removed and the new pile takes their place.

If the active player has no legal fusion, the game is over and that player loses. In other words, the player who makes the final legal fusion wins.

Both players play optimally. Return True if the first player wins, otherwise False.

Function

Implement first_player_wins(piles, limit), where:

  • piles is a list of integers giving the pile sizes.
  • limit is the maximum size a fused pile may have.
  • The return value is a boolean.

Pile order is irrelevant: two arrangements with the same multiset of sizes are the same position.

Constraints

  • 1 <= len(piles) <= 10
  • 1 <= limit <= 100
  • 1 <= piles[i] <= limit

Examples

Example 1

Input: first_player_wins([2, 2, 2], 5)

Output: True

Example 2

Input: first_player_wins([3, 3], 5)

Output: False

Hints

Hint 1

Treat it as a standard win/lose game: a position is winning if at least one legal fusion leads to a losing position for the opponent, and losing if there is no move or every move leads to a winning position.

Hint 2

Order of piles does not matter, so represent a position as a sorted tuple. Different fusion orders often reach the same multiset, so cache results per tuple.

Hint 3

Each fusion reduces the number of piles by one, so the game always ends within n - 1 moves and there are no cycles. Plain recursion with memoization is enough for n <= 10.