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
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 his/her friend. In each round, a player can remove any two consecutive candies with the same value. And whoever can not pick up a candy loses and that player1 start first, we have to check whether player1 will win or not.
So, if the input is like nums = [2, 2, 5], then the output will be True, as if player1 picks the 2s then the other player cannot pick any candies.
To solve this, we will follow these steps:
stack := a new stack
turns := 0
-
for each num in nums, do
-
if stack is not empty and top of stack is same as num, then
pop from stack
turns := turns + 1
-
otherwise,
push num into stack
-
return true when turns is odd otherwise false
Example
class Solution: def solve(self, nums): stack = [] turns = 0 for num in nums: if stack and stack[-1] == num: stack.pop() turns += 1 else: stack.append(num) return bool(turns & 1) ob = Solution() nums = [2, 2, 5] print(ob.solve(nums))
Input
[2, 2, 5]
Output
True
