Predict the Winner (LeetCode 486): Solution and Explanation

Medium
Array
Math
Dynamic Programming
Recursion
Game Theory

Two players take turns removing a number from either end of nums and adding it to their score. Player 1 moves first, both play optimally, and you return true if player 1 finishes with at least as many points as player 2.

Intuition

Greedy fails. In [3, 9, 1, 2] taking the bigger end (3) hands the 9 to player 2; taking 2 instead forces player 2 to open up the 9 for player 1.

What remains after any sequence of moves is always a contiguous window nums[i..j]. That window, plus whose turn it is, is the whole game state.

Store the score difference instead of two scores. If dp[i][j] is how far ahead the player to move can finish on the window, the same table works for both players.

Taking nums[i] gains that number, and then the opponent becomes the player to move on nums[i+1..j] and gets ahead by dp[i+1][j]. So the move is worth nums[i] - dp[i+1][j]. The right end is the mirror image.

Approach: Interval DP on the score lead

  1. Create an n x n table and set dp[i][i] = nums[i].
  2. For window length 2 up to n, for each start i with end j = i + length - 1:
  3. Set dp[i][j] = max(nums[i] - dp[i+1][j], nums[j] - dp[i][j-1]).
  4. Return dp[0][n-1] >= 0.

Step-by-step example

nums = [1, 5, 233, 7]
  1. Diagonal: dp = 1, 5, 233, 7 for the single numbers.
  2. Length 2: [1,5] → max(1 - 5, 5 - 1) = 4; [5,233] → 228; [233,7] → 226.
  3. Length 3: [1,5,233] → max(1 - 228, 233 - 4) = 229; [5,233,7] → max(5 - 226, 7 - 228) = -221.
  4. Length 4: [1,5,233,7] → max(1 - (-221), 7 - 229) = 222.
  5. dp[0][3] = 222 >= 0, so return true: player 1 takes 1 and later gets 233.

Code: Python, Java, C++

1class Solution:
2    def predictTheWinner(self, nums: List[int]) -> bool:
3        n = len(nums)
4        dp = [[0] * n for _ in range(n)]
5        for i in range(n):
6            dp[i][i] = nums[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(nums[i] - dp[i + 1][j], nums[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 about n²/2 windows and each is filled in O(1).

Space

O(n^2)

The table; it can be cut to O(n) with a single row because each length only needs the previous one.

Other approaches

Minimax recursion with memo (time O(n^2), space O(n^2))

f(i, j) returns the best lead on nums[i..j], computed as max(nums[i] - f(i+1, j), nums[j] - f(i, j-1)) with a memo table. Same recurrence, top-down.

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

Try both ends at every turn without memo. With n at most 20 this is about a million paths and still passes, but it does not scale.

Even-length shortcut (time O(1) for even n, space O(1))

When n is even, player 1 can always take all even-index or all odd-index numbers, so they never lose. This answers half the cases instantly, but odd lengths still need the DP.

Common mistakes

  • Playing greedily by always taking the bigger end. [3, 9, 1, 2] shows it can lose a game player 1 can win.
  • Returning dp[0][n-1] > 0. A tie counts as a win for player 1, so the check is >= 0.
  • Tracking two scores and forgetting whose turn it is. The difference formulation removes that bookkeeping.
  • Filling the table in the wrong order. dp[i][j] needs dp[i+1][j] and dp[i][j-1], so go by increasing window length (or i from high to low).

Frequently asked questions

Why does subtracting dp of the rest work?

After you take an end, the opponent moves on the smaller window and, playing optimally, finishes ahead by dp of that window counted from their side. Your lead on the full window is what you took minus that.

Does player 2 need a separate table?

No. dp is always from the view of whoever moves next on that window, so it already describes player 2 on the windows they face.

How is this related to Stone Game?

Stone Game is the same game with an even number of piles and an odd total, where player 1 always wins. Predict the Winner allows any length and ties, so you actually have to compute the DP.