Coin Pile Fusion: Who Makes the Last Merge?
Dynamic ProgrammingAuto-graded · 22 test casesLast 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:
pilesis a list of integers giving the pile sizes.limitis 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) <= 101 <= limit <= 1001 <= 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a finite impartial game under normal play: the player who cannot move loses. We use the usual recursion:
- A position is losing if there is no legal fusion, or if every legal fusion leads to a winning position for the opponent.
- A position is winning if some legal fusion leads to a losing position for the opponent.
We represent a position as a sorted tuple of pile sizes. This is canonical (order does not matter) and hashable, so it works as a memoization key. From a position we try every pair (i, j) with state[i] + state[j] <= limit, build the successor by removing both piles and inserting their sum, sort, and recurse. As soon as a successor is losing for the opponent, we return True.
Why it is correct
- Termination: every fusion reduces the pile count by exactly one, so a game lasts at most
n - 1moves and the position graph is acyclic. The recursion therefore always reaches a base case. - Base case: if no pair has a sum within
limit, the loops find nothing and we returnFalse, since the player to move loses. - Induction: assuming the result is right for all positions with
m - 1piles, a position withmpiles is reported winning exactly when some move reaches a position reported losing, which is the definition of a winning position under optimal play. - Memoization is valid: the outcome depends only on the multiset of sizes and the fixed
limit, not on how the position was reached.
Edge cases: a single pile has no pairs, so the answer is False. If no pair fits under the limit, the answer is False. A pile equal to limit can never be fused again and just stays in the tuple.
Complexity
Each reachable position corresponds to a grouping of the original piles, so the number of distinct positions S is at most the Bell number B(n) (B(10) = 115,975), and typically far fewer because equal multisets collapse and the limit prunes moves.
- Time:
O(S * n^3 log n)in the worst case (aboutn^2pairs per state, each successor costsO(n log n)to build). - Space:
O(S * n)for the memo table plusO(n)recursion depth.
Reference solution
from functools import lru_cache
from typing import List
def first_player_wins(piles: List[int], limit: int) -> bool:
@lru_cache(maxsize=None)
def winning(state):
m = len(state)
for i in range(m):
for j in range(i + 1, m):
merged = state[i] + state[j]
if merged <= limit:
nxt = list(state[:i] + state[i + 1:j] + state[j + 1:])
nxt.append(merged)
nxt.sort()
if not winning(tuple(nxt)):
return True
return False
return winning(tuple(sorted(piles)))