464. Can I Win
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
This is a classic two-player combinatorial game. Both players play optimally, which suggests a minimax approach. We need to determine if the first player can force a win. This can typically be solved using recursion with memoization (or top-down dynamic programming).
Solution
Can I Win in Python
class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
# If desiredTotal is 0 or less, the first player wins immediately.
if desiredTotal <= 0:
return True
# If the sum of all available numbers is less than desiredTotal, no one can win.
if (maxChoosableInteger * (maxChoosableInteger + 1)) // 2 < desiredTotal:
return False
# memo dictionary to store results of subproblems.
# Key: bitmask of used numbers. Value: boolean win/loss.
self.memo = {}
# The state is represented by a bitmask of used numbers.
# 0 means no number is used yet.
return self.solve(maxChoosableInteger, desiredTotal, 0)
def solve(self, max_val: int, remaining_total: int, mask: int) -> bool:
# If this state (mask) is already computed, return the stored result.
if mask in self.memo:
return self.memo[mask]
# Iterate through all possible numbers to choose.
for i in range(1, max_val + 1):
# Check if the number 'i' is available (i-th bit is not set in mask).
if not (mask & (1 << (i - 1))):
# If choosing 'i' wins the game immediately.
if i >= remaining_total:
self.memo[mask] = True
return True
# Recursive step: check if the opponent can be forced into a losing position.
# If the opponent CANNOT win from the new state, it means we have found a winning move.
new_mask = mask | (1 << (i - 1))
if not self.solve(max_val, remaining_total - i, new_mask):
self.memo[mask] = True
return True
# If the loop finishes, it means no winning move was found for the current player.
self.memo[mask] = False
return False
Can I Win in Java
class Solution {
// Memoization array. Using Boolean to represent three states: null (not computed), true (win), false (lose).
private Boolean[] memo;
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
// If desiredTotal is 0 or less, the first player wins without making a move.
if (desiredTotal <= 0) {
return true;
}
// Calculate the sum of all choosable numbers.
int sum = maxChoosableInteger * (maxChoosableInteger + 1) / 2;
// If even with all numbers, the total cannot be reached, no one can win.
if (sum < desiredTotal) {
return false;
}
// Initialize memoization table.
memo = new Boolean[1 << maxChoosableInteger];
// Start the recursive search.
return solve(maxChoosableInteger, desiredTotal, 0);
}
private boolean solve(int maxChoosableInteger, int remainingTotal, int mask) {
// If remainingTotal is non-positive, it means the previous player already won.
// So the current player loses.
// This is implicitly handled by the loop logic, but can be an explicit base case.
// if (remainingTotal <= 0) return false;
// If we have computed the result for this state (mask), return it.
if (memo[mask] != null) {
return memo[mask];
}
// Iterate through all possible numbers to choose.
for (int i = 1; i <= maxChoosableInteger; i++) {
// Check if the i-th bit is set, meaning number 'i' is used.
if ((mask & (1 << (i - 1))) == 0) {
// If choosing 'i' wins the game immediately.
if (i >= remainingTotal) {
memo[mask] = true;
return true;
}
// Try choosing 'i'. If the other player *cannot* win from the new state, then we win.
int newMask = mask | (1 << (i - 1));
if (!solve(maxChoosableInteger, remainingTotal - i, newMask)) {
memo[mask] = true;
return true;
}
}
}
// If we've tried all available numbers and couldn't force a win, we lose from this state.
memo[mask] = false;
return false;
}
}
Can I Win in C++
class Solution {
public:
bool canIWin(int maxChoosableInteger, int desiredTotal) {
// If desiredTotal is 0 or less, the first player wins immediately.
if (desiredTotal <= 0) {
return true;
}
// Calculate the sum of all choosable numbers.
int sum = maxChoosableInteger * (maxChoosableInteger + 1) / 2;
// If the sum is less than desiredTotal, no one can win.
if (sum < desiredTotal) {
return false;
}
// Memoization table: 0: uncomputed, 1: win, -1: lose
memo.assign(1 << maxChoosableInteger, 0);
return solve(maxChoosableInteger, desiredTotal, 0);
}
private:
vector<int> memo;
bool solve(int maxChoosableInteger, int desiredTotal, int mask) {
// If the desiredTotal is met or exceeded by the previous player, the current player loses.
if (desiredTotal <= 0) {
return false;
}
// If this state has been computed, return the result.
if (memo[mask] != 0) {
return memo[mask] == 1;
}
// Try every possible move for the current player.
for (int i = 1; i <= maxChoosableInteger; ++i) {
// Check if the number 'i' is not used yet.
if (!((mask >> (i - 1)) & 1)) {
// If the opponent cannot win after we choose 'i', then we win.
// The opponent's goal is now to reach the new desiredTotal (desiredTotal - i).
if (!solve(maxChoosableInteger, desiredTotal - i, mask | (1 << (i - 1)))) {
memo[mask] = 1; // Mark current state as a winning state.
return true;
}
}
}
// If no winning move is found, the current player loses.
memo[mask] = -1; // Mark current state as a losing state.
return false;
}
};
Can I Win in TypeScript
function canIWin(maxChoosableInteger: number, desiredTotal: number): boolean {
// If desiredTotal is 0 or less, the first player wins immediately.
if (desiredTotal <= 0) {
return true;
}
// Calculate the sum of all available numbers.
const sum = (maxChoosableInteger * (maxChoosableInteger + 1)) / 2;
// If the sum is less than desiredTotal, no one can win.
if (sum < desiredTotal) {
return false;
}
// Memoization map. Key: mask, Value: boolean win/loss.
const memo = new Map<number, boolean>();
function solve(remainingTotal: number, mask: number): boolean {
// If the result for this state is already computed, return it.
if (memo.has(mask)) {
return memo.get(mask)!;
}
// Iterate through all possible numbers to choose.
for (let i = 1; i <= maxChoosableInteger; i++) {
// Check if the number 'i' is available.
if (!((mask >> (i - 1)) & 1)) {
// If choosing 'i' wins the game immediately.
if (i >= remainingTotal) {
memo.set(mask, true);
return true;
}
// Recursive step: If the opponent cannot win from the new state, we win.
const newMask = mask | (1 << (i - 1));
if (!solve(remainingTotal - i, newMask)) {
memo.set(mask, true);
return true;
}
}
}
// If no winning move is found, the current player loses.
memo.set(mask, false);
return false;
}
// Initial call for the first player with an empty mask.
return solve(desiredTotal, 0);
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.