Stone Game (LeetCode 877): Solution and Explanation

Medium
Array
Math
Dynamic Programming
Game Theory

Alice and Bob take turns removing a pile from either end of a row. With both playing perfectly, decide whether Alice, who moves first, ends with more stones.

Intuition

Two scores are awkward to track, but in a zero-sum game one number is enough: how far ahead the player to move can finish on what is left. Call it the lead.

If piles i..j remain and you take the left pile, you gain piles[i] and your opponent becomes the mover on i+1..j, where they can get a lead of dp[i+1][j]. Your net lead is piles[i] - dp[i+1][j]. The right end works the same way, and you pick the better of the two.

Every window depends only on windows one pile shorter, so filling the table by window length works. Alice wins exactly when her lead on the whole row is positive.

Approach: Interval DP on the mover's lead

  1. Let dp[i][j] be the most the player to move can finish ahead when only piles[i..j] remain.
  2. One pile: dp[i][i] = piles[i].
  3. For window length 2 up to n and each start i, with j = i + length - 1, set dp[i][j] = max(piles[i] - dp[i+1][j], piles[j] - dp[i][j-1]).
  4. Return dp[0][n-1] > 0.

Step-by-step example

piles = [5,3,4,5]
  1. Single piles: dp[0][0] = 5, dp[1][1] = 3, dp[2][2] = 4, dp[3][3] = 5.
  2. Length 2: dp[0][1] = max(5 - 3, 3 - 5) = 2, dp[1][2] = max(3 - 4, 4 - 3) = 1, dp[2][3] = max(4 - 5, 5 - 4) = 1.
  3. Length 3: dp[0][2] = max(5 - 1, 4 - 2) = 4 and dp[1][3] = max(3 - 1, 5 - 1) = 4.
  4. Length 4: dp[0][3] = max(5 - 4, 5 - 4) = 1.
  5. dp[0][3] = 1 > 0, so with both sides playing perfectly Alice finishes one stone ahead, 9 to 8. The answer is true.

Code: Python, Java, C++

1class Solution:
2    def stoneGame(self, piles: List[int]) -> bool:
3        n = len(piles)
4        dp = [[0] * n for _ in range(n)]
5        for i in range(n):
6            dp[i][i] = piles[i]
7        for length in range(2, n + 1):
8            for i in range(n - length + 1):
9                j = i + length - 1
10                dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1])
11        return dp[0][n - 1] > 0
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

There are n(n+1)/2 windows and each is filled in constant time.

Space

O(n^2)

The table holds one value per window. Since each length only reads the previous length, a single array of size n can be reused.

Other approaches

Parity argument (time O(1), space O(1))

Colour the piles by even and odd index. Moving first with an even count, Alice can always take every pile of one colour, so she picks the colour with the larger total and never loses. The function can return true directly.

Memoised recursion (time O(n^2), space O(n^2))

Recurse on (i, j) with the same max formula and cache results. Same complexity as the table, top-down.

Common mistakes

  • Tracking Alice's score alone. Whose turn it is depends on the window, so storing the mover's lead avoids carrying a turn flag.
  • Adding the opponent's lead instead of subtracting it. After you move, the opponent's lead counts against you.
  • Filling the table by rows from the top. dp[i][j] needs dp[i+1][j], so fill by window length or with i going downward.
  • Comparing dp[0][n-1] with 0 using >=. Ties are impossible here because the total is odd, but > is the honest test.

Frequently asked questions

Why is the answer always true?

With an even number of piles, the first player can take every even-indexed pile or every odd-indexed pile, whichever set sums higher. The totals differ because the sum is odd, so Alice always wins.

Then why learn the DP?

The parity trick breaks as soon as the rules change: an odd number of piles, ties allowed, or variants like Stone Game II and Predict the Winner. The lead DP handles all of those.

What does a negative dp value mean?

The player to move on that window will finish behind no matter what they do. It can happen on odd-length windows, where the mover gets one more pile but a worse set.