Magicsheet logo

Stone Game IV

Hard
37.5%
Updated 8/1/2025

Stone Game IV

What is this problem about?

Stone Game IV is a game where Alice and Bob take turns removing a non-zero square number of stones (1, 4, 9, 16, ...) from a single pile of nn stones. The player who takes the last stone wins. You need to determine if Alice (the first player) can win given nn stones.

Why is this asked in interviews?

This problem is a pure test of Game Theory and Dynamic Programming. It assesses whether you can recognize a "winning state" vs a "losing state." It's common in Microsoft interviews to see if a candidate can optimize a recursive solution with memoization or implement an iterative DP approach efficiently.

Algorithmic pattern used

The pattern is Dynamic Programming.

  • Winning State: A state nn is a winning state if there exists some square number k2nk^2 \le n such that nk2n - k^2 is a losing state.
  • Losing State: A state nn is a losing state if for all possible square numbers k2nk^2 \le n, nk2n - k^2 is a winning state. We can build a boolean DP array canWin[n+1] where canWin[i] is true if the current player can win starting with ii stones.

Example explanation (use your own example)

Let n=7n = 7.

  • i=0i=0: False (Losing state).
  • i=1i=1: Can take 12=11^2=1. 11=01-1=0 (Losing). So 1 is Winning (True).
  • i=2i=2: Can only take 1. 21=12-1=1 (Winning). So 2 is Losing (False).
  • i=3i=3: Can only take 1. 31=23-1=2 (Losing). So 3 is Winning (True).
  • i=4i=4: Can take 22=42^2=4. 44=04-4=0 (Losing). So 4 is Winning (True).
  • i=5i=5: Can take 1 or 4. 51=45-1=4 (W), 54=15-4=1 (W). All lead to Winning states, so 5 is Losing (False).
  • i=6i=6: Can take 1 or 4. 61=56-1=5 (L), so 6 is Winning (True).
  • i=7i=7: Can take 1 or 4. 74=37-4=3 (W), 71=67-1=6 (W). Wait, if 74=37-4=3 and 3 is Winning, and 71=67-1=6 and 6 is Winning, then 7 is a losing state? No, we check if any move leads to a false. 71=6(T)7-1=6(T), 74=3(T)7-4=3(T). Both true, so 7 is False.

Common mistakes candidates make

  • Slow iteration: Not optimizing the inner loop that checks square numbers (O(NN)O(N \sqrt{N}) is the goal).
  • Base case: Not realizing that 0 stones is a losing state for the person whose turn it is.
  • Confusing Win/Loss: Forgetting the logic that "I win if I can force you to lose."
  • Greedy logic: Thinking that taking the largest possible square is always the best move (it's not; any square that leads to a losing state is fine).

Interview preparation tip

Game Theory problems often boil down to: "Can I make a move such that the remaining game state is a loss for my opponent?" This simple boolean logic is the heart of many Hard coding problems.

Similar Questions