Two players share a pool of the whole numbers 1 to maxChoosableInteger. They take turns. On a turn, a player removes one number from the pool and adds it to a running total that starts at 0. A number, once taken, is gone for good.
Whoever makes the running total reach desiredTotal or more wins. Both players play perfectly. Return true if the player who moves first can always win, and false otherwise.
Example 1
Input: maxChoosableInteger = 3, desiredTotal = 4 Output: false Why: after any first pick, the reply finishes it
2 more examples and the constraints
Example 2
Input: maxChoosableInteger = 4, desiredTotal = 6 Output: true Why: take 1; any reply (2, 3 or 4) can then be finished
Example 3
Input: maxChoosableInteger = 5, desiredTotal = 50 Output: false Why: 1 + 2 + 3 + 4 + 5 = 15, so 50 is never reached
Constraints
- 1 ≤ maxChoosableInteger ≤ 20
- 0 ≤ desiredTotal ≤ 300
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Memo keyed by the used setO(2ⁿ · n²)
- Bitmask memoO(2ⁿ · n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 20 | Verdict |
|---|---|---|---|
| Memo keyed by the used set | O(2ⁿ · n²) | Passes; heavy keys | |
| Bitmask memo | O(2ⁿ · n) | Best; one integer per state |
n = maxChoosableInteger.
Edge cases to test
- desiredTotal is 0. Any first pick reaches it, so the answer is true.
- Total out of reach. If 1 + ... + n < desiredTotal nobody wins: return false before searching.
- Sum equals the total. All numbers get used, so whoever takes the last one wins: true for an odd count (19), false for an even one (6 or 20).
- A first pick that wins at once. If n ≥ desiredTotal, picking n wins immediately: (7, 1) is true.
Common mistakes
- Keying the memo by the remaining total alone. Different used sets can need the same amount and have different answers.
- Skipping the sum check, so an unreachable total is searched and answered by accident.
- Reading "the opponent wins from there" as good for you; you want the opponent to lose.
How to talk through it
- 1Clarify. Does reaching the total exactly or going over both win? Can a number be used twice? What if desiredTotal is 0?
- 2Define a winning position. The mover wins if some pick reaches the total or leaves the opponent in a losing position.
- 3Spot the repeated states. Different pick orders reach the same used set, and the needed amount follows from that set.
- 4Code the bitmask memo. One bit per number, an array of 2ⁿ results, and the sum check up front.
- 5Test out loud. Run a total of 0, a total out of reach and a sum that equals the total before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?