Predict the Winner solution explained

Predict the Winner gives two players a row of scores; they take turns removing a number from either end, and you must say whether the first player can finish with at least as many points as the second when both play perfectly. Define best(i, j) as the largest lead the player to move can secure on the slice from i to j: it is the larger of nums[i] - best(i + 1, j) and nums[j] - best(i, j - 1). The first player wins or ties exactly when best(0, n - 1) >= 0. That is O(n²) time, and the table fits in one array of length n.

By Published 8 min read

The problem, restated

A row of non-negative integers sits on the table. Player one moves first, then the players alternate. On each turn the player takes the number at the left end or the right end of what remains and adds it to their score. When the row is empty, compare the scores. Return true if player one can make sure their score is greater than or equal to player two's, assuming player two also plays as well as possible.

Examples written for this page (best play, printed by the code below)
RowPlayer one, player twoResult
[2, 7, 3]5, 7false: whichever end player one takes, player two gets the 7
[4, 1, 2, 6]8, 5true
[1, 1]1, 1true: a tie counts
[6, 2, 9, 4, 1]12, 10true
[5]5, 0true
Examples written for this page (best play, printed by the code below). Scroll sideways on a small screen.

What the interviewer is checking

This is the entry point to two-player game DP, and the interviewer wants to see the minimax idea expressed cleanly. Candidates who track two separate totals and alternate turns in their recursion usually tangle themselves. Candidates who say "each state is a slice, and its value is the best lead for whoever moves next" get a two-line recurrence. After that, the interviewer may ask you to fill the table bottom-up, cut it to one row, or explain why even-length rows are always a win for the first player.

Questions before coding

  • Does a tie count as a win for player one? Here it does, so compare with >= 0.
  • Can values be negative? Assume not, but the difference recurrence works either way.
  • Do you need the scores or just the verdict? The verdict; the scores follow from the lead and the total if asked.

Brute force: play every game

A direct recursion tries both ends at every turn and lets each player choose the move that is best for them. Without memory of earlier work it explores up to 2^n move sequences, so it only works for very short rows. It is still worth writing in your head, because the memoized version is the same recursion with a cache.

The score-difference recurrence

Look at any slice of the row, from index i to index j, with some player to move. Whatever happened before does not matter: the points already taken are fixed, and the rest of the game depends only on this slice. So give the slice a value, best(i, j), the largest lead the mover can guarantee over the other player on these numbers alone. If the mover takes nums[i], the opponent then moves on the slice i + 1 to j and secures a lead of best(i + 1, j) there, so the mover's net lead is nums[i] - best(i + 1, j). Taking the right end works the same way. The mover picks the larger.

from functools import lru_cache

def first_player_can_win(nums):
    @lru_cache(maxsize=None)
    def lead(i, j):
        if i == j:
            return nums[i]
        return max(nums[i] - lead(i + 1, j), nums[j] - lead(i, j - 1))

    return lead(0, len(nums) - 1) >= 0
Python: memoized recursion on (i, j). O(n^2) states, O(1) work each.

Python's default recursion limit is around a thousand frames, and this recursion can go as deep as n. For long inputs, fill the table bottom-up instead.

Bottom-up in one array

best(i, j) depends on best(i + 1, j), the row below, and best(i, j - 1), the entry to its left in the same row. So process i from the last index down to 0 and, within each i, j from i + 1 upward. A single array can hold the current row: before it is overwritten, dp[j] still holds best(i + 1, j), and dp[j - 1] already holds the new best(i, j - 1).

def first_player_can_win_table(nums):
    n = len(nums)
    dp = list(nums)
    for i in range(n - 2, -1, -1):
        for j in range(i + 1, n):
            dp[j] = max(nums[i] - dp[j], nums[j] - dp[j - 1])
    return dp[n - 1] >= 0
Python: one array, O(n^2) time, O(n) memory.
function predictTheWinner(nums) {
  const n = nums.length;
  const dp = nums.slice();
  for (let i = n - 2; i >= 0; i--) {
    for (let j = i + 1; j < n; j++) {
      dp[j] = Math.max(nums[i] - dp[j], nums[j] - dp[j - 1]);
    }
  }
  return dp[n - 1] >= 0;
}
JavaScript: the same single-array fill.

Trace on [2, 7, 3]

best(i, j) for every slice; the answer is in the last row
SliceTake leftTake rightbest
[2], [7], [3]2, 7, 3
[2, 7]2 - 7 = -57 - 2 = 55
[7, 3]7 - 3 = 43 - 7 = -44
[2, 7, 3]2 - best[7, 3] = 2 - 4 = -23 - best[2, 7] = 3 - 5 = -2-2
best(i, j) for every slice; the answer is in the last row. Scroll sideways on a small screen.

The final value is -2, so player one ends two points behind, matching 5 against 7 in the examples table.

Why even-length rows always favor player one

Color the positions alternately, even indexes and odd indexes. With an even count, the two ends always have different colors at player one's turn, and player one can always take a number of the same color, leaving two ends of the other color for player two. So player one can collect every even-indexed number or every odd-indexed number, whichever group sums higher, and that sum is at least half the total. This guarantees a tie or better, which is why the answer for even n is always true. It does not tell you the best score, and it says nothing about odd lengths, so treat it as a check, not the solution.

Complexity

n numbers in the row
ApproachTimeExtra memory
Play every move sequenceO(2^n)O(n) stack
Memoized recursionO(n²)O(n²) cache, O(n) stack
Table in one arrayO(n²)O(n)
n numbers in the row. Scroll sideways on a small screen.

Edge cases

  • One number: player one takes it and wins.
  • All zeros: every game is a tie, so the answer is true.
  • Two equal numbers: a tie, true.
  • Odd length where the middle value is huge, like [1, 50, 1]: player one cannot avoid handing it over, so the answer is false.
  • Long rows: use the table, not deep recursion.

Common mistakes

  • Greedy play, always taking the larger end. On [1, 2, 5, 3], grabbing the 3 lets player two take the 5 and win 6 to 5, while opening with the 1 wins 6 to 5 for player one.
  • Tracking whose turn it is and adding or subtracting depending on the player, which doubles the states and invites sign errors.
  • Comparing with > 0 and treating a tie as a loss.
  • Filling the table in the wrong order, so best(i + 1, j) is read before it is computed.
  • Relying on the even-length shortcut and skipping the DP for odd lengths.

How to explain it out loud

Fictional example

Turning a game into a lead
Candidate
Once some numbers are gone, the game only depends on the slice that is left and who moves. So I define the value of a slice as the best lead the mover can get over the other player on it.
Candidate
If I take the left number, my opponent then gets their best lead on the rest, so my net is that number minus their lead. Same for the right. I take the max. Player one wins or ties if the whole row's value is at least zero.
Interviewer
Can you do it without recursion?
Candidate
Yes. Each slice needs the slice one shorter on either side, so I fill by start index from the right and end index going up, and one array is enough.

Stone Game II adds a growing move limit to the same take-turns structure and uses the same subtract-the-opponent trick. Guess Number Higher or Lower II is another minimax over intervals, where you pay for guesses against an adversary. Longest Common Subsequence is a good comparison for how a two-index table is filled in the right order.

Practicing with Natively

Game DP is easiest to learn by explaining the state out loud until it sounds obvious. Do that in a mock interview on Mac or Windows with Natively transcribing, then read back whether you defined best(i, j) before writing code. When you have made your own attempt, Natively can read the problem from a screenshot and suggest an approach to set beside yours. See the AI interview assistant.

Questions people ask

How do you solve Predict the Winner?

Define best(i, j) as the largest lead the player to move can secure on the slice from i to j. It is the larger of nums[i] - best(i + 1, j) and nums[j] - best(i, j - 1), with best(i, i) = nums[i]. Player one wins or ties exactly when best(0, n - 1) is at least 0.

What is the time complexity of Predict the Winner?

O(n²) time. Memoized recursion uses an O(n²) cache, while filling the table bottom-up needs only one array of length n. Playing out every move sequence without memory is O(2^n).

Does the first player always win with an even number of values?

Yes, player one can always tie or win: they can collect every even-indexed number or every odd-indexed number, whichever sums higher. That says nothing about odd lengths, so use it as a check, not the solution.

Why does greedy play fail in Predict the Winner?

Always taking the larger end can hand over a bigger number. On [1, 2, 5, 3], taking the 3 lets player two take the 5 and win 6 to 5, while opening with the 1 wins 6 to 5 for player one.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP