Alice and Bob face a row of piles of stones, piles[i] stones in pile i. The number of piles is even, and the total number of stones is odd, so a draw is impossible.
They take turns, Alice first. On a turn, a player removes a whole pile from either the left end or the right end of the row and keeps it. When no piles are left, whoever holds more stones wins.
If both play as well as possible, return true when Alice wins and false when Bob wins.
Example 1
Input: piles = [2,6,3,2] Output: true Why: Alice can take both odd positions, 6 + 2 = 8 against 5
2 more examples and the constraints
Example 2
Input: piles = [9,2] Output: true Why: Alice takes 9 and Bob gets 2
Example 3
Input: piles = [1,8,2,7,4,3] Output: true Why: the odd positions hold 18 of the 25 stones
Constraints
- 2 ≤ length of piles ≤ 500, and the length is even
- 1 ≤ piles[i] ≤ 500
- The sum of all piles is odd
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Minimax with memoO(n²)
- Bottom-up tableO(n²)
- Even or odd positionsO(1)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 500 piles | Verdict |
|---|---|---|---|
| Minimax with memo | O(n²) | Passes; works for any row | |
| Bottom-up table | O(n²) | Passes; no recursion | |
| Even or odd positions | O(1) | Best; relies on even count, odd total |
n = number of piles.
Edge cases to test
- Two piles. Alice takes the bigger one; they cannot be equal because the total is odd.
- Greedy fails. In [3,9,1,2], taking the bigger end, 3, lets Bob take 9. Alice must take 2 first, and then the 9 is hers.
- Big pile in the middle. [1,100,1,1]: Alice takes a 1 at the right end so that Bob cannot reach the 100 first.
- Largest input. 500 piles is 125,250 ranges for the DP, which is still fast.
Common mistakes
- Playing greedily, always taking the bigger end, which can hand the opponent a large pile.
- Tracking only Alice's score in the DP and forgetting that Bob also plays to win.
- Giving
return truewith no reason; the interviewer wants the colour argument.
How to talk through it
- 1Clarify. Is the number of piles always even and the total always odd? Can only the ends be taken?
- 2Model it. Let lead(i, j) be the best lead of the player to move; the opponent's lead is subtracted.
- 3Code the DP. Memo or table over all ranges, O(n²), then check lead(0, n − 1) > 0.
- 4Spot the shortcut. Colour even and odd positions; Alice can force a whole colour, so she always wins.
- 5Test out loud. Run two piles and [1,100,1,1], where the middle pile must be protected.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?