Find the Winning Player in Coin Game
Problem
You are given two positive integers x and y, denoting the number of coins with values 75 and 10 respectively.
Alice and Bob are playing a game. Each turn, starting with Alice , the player must pick up coins with a total value 115. If the player is unable to do so, they lose the game.
Return the name of the player who wins the game if both players play optimally.
Examples
Example 1
Input: x = 2, y = 7
Output: "Alice"
Explanation:
The game ends in a single turn:
* Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.
Example 2
Input: x = 4, y = 11
Output: "Bob"
Explanation:
The game ends in 2 turns:
* Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.
* Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.
Constraints
1 <= x, y <= 100
Solution
Method 1 – Greedy Simulation
Intuition
Each player must pick coins with a total value of 115. There are only two coin types: 75 and 10. The only possible ways to make 115 are:
- 1 coin of 75 and 4 coins of 10 (75 + 10*4 = 115)
- 0 coins of 75 and 11 coins of 10 (10*11 = 110, not enough)
- 2 coins of 75 and -35 coins of 10 (not possible)
- 0 coins of 75 and 11 coins of 10 (not possible) So, the only way is to pick 1 coin of 75 and 4 coins of 10.
The game proceeds turn by turn. If at any turn, the player cannot pick 1 coin of 75 and 4 coins of 10, they lose. The number of turns possible is the minimum of x (number of 75 coins) and y // 4 (number of 10 coins divided by 4).
If the number of turns is odd, Alice wins (since she starts first), otherwise Bob wins.
Approach
- For each turn, check if there is at least 1 coin of 75 and 4 coins of 10 left.
- The maximum number of turns is min(x, y // 4).
- If the number of turns is odd, Alice wins; else, Bob wins.
Code
C++
class Solution {
public:
string findWinner(int x, int y) {
int turns = min(x, y / 4);
return (turns % 2 == 1) ? "Alice" : "Bob";
}
};
Go
func findWinner(x, y int) string {
turns := x
if y/4 < x {
turns = y / 4
}
if turns%2 == 1 {
return "Alice"
}
return "Bob"
}
Java
class Solution {
public String findWinner(int x, int y) {
int turns = Math.min(x, y / 4);
return (turns % 2 == 1) ? "Alice" : "Bob";
}
}
Kotlin
class Solution {
fun findWinner(x: Int, y: Int): String {
val turns = minOf(x, y / 4)
return if (turns % 2 == 1) "Alice" else "Bob"
}
}
Python
class Solution:
def findWinner(self, x: int, y: int) -> str:
turns = min(x, y // 4)
return "Alice" if turns % 2 == 1 else "Bob"
Rust
impl Solution {
pub fn find_winner(x: i32, y: i32) -> String {
let turns = x.min(y / 4);
if turns % 2 == 1 { "Alice".to_string() } else { "Bob".to_string() }
}
}
TypeScript
class Solution {
findWinner(x: number, y: number): string {
const turns = Math.min(x, Math.floor(y / 4));
return turns % 2 === 1 ? "Alice" : "Bob";
}
}
Complexity
- ⏰ Time complexity:
O(1)— Only a few arithmetic operations. - 🧺 Space complexity:
O(1)— No extra space used.