Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether first player win in candy remove game or not in Python?
Suppose we have a list of numbers called candies and someone is playing a game against their friend. In each round, a player can remove any two consecutive candies with the same value. Whoever cannot pick up any candies loses. If player1 starts first, we have to check whether player1 will win or not.
So, if the input is like candies = [2, 2, 5], then the output will be True, as if player1 picks the consecutive 2s, then the other player cannot pick any candies and loses.
Algorithm
To solve this, we will follow these steps ?
Create an empty stack
Initialize turns counter to 0
-
For each candy in the list ?
-
If stack is not empty and top of stack equals current candy, then
Pop from stack (remove the pair)
Increment turns counter
Otherwise, push current candy into stack
-
Return True if turns is odd (player1 wins), False otherwise
Example
Let's implement this solution ?
class Solution:
def solve(self, candies):
stack = []
turns = 0
for candy in candies:
if stack and stack[-1] == candy:
stack.pop()
turns += 1
else:
stack.append(candy)
return bool(turns & 1)
# Test the solution
ob = Solution()
candies = [2, 2, 5]
print(ob.solve(candies))
True
How It Works
The algorithm uses a stack to simulate the game. When we encounter a candy that matches the top of the stack, it represents a valid move (removing two consecutive identical candies). Each valid move increments the turn counter. Since player1 starts first, an odd number of turns means player1 made the last move and wins.
Additional Examples
Let's test with different inputs ?
class Solution:
def solve(self, candies):
stack = []
turns = 0
for candy in candies:
if stack and stack[-1] == candy:
stack.pop()
turns += 1
else:
stack.append(candy)
return bool(turns & 1)
ob = Solution()
# Test case 1: Player1 wins
print("Test 1:", ob.solve([2, 2, 5]))
# Test case 2: Player1 loses (no moves possible)
print("Test 2:", ob.solve([1, 2, 3]))
# Test case 3: Player1 loses (even number of moves)
print("Test 3:", ob.solve([1, 1, 2, 2]))
Test 1: True Test 2: False Test 3: False
Conclusion
This candy removal game can be solved using a stack-based approach that counts valid moves. Player1 wins if the total number of moves is odd, since they make the first move and alternate with player2.
