Program to check whether first player win in candy remove game or not in Python?

PythonServer Side ProgrammingProgramming

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


 Live Demo

class Solution:
   def solve(self, nums):
      stack = []
      turns = 0
      for num in nums:
         if stack and stack[-1] == num:
            turns += 1

      return bool(turns & 1)

ob = Solution()
nums = [2, 2, 5]


[2, 2, 5]


Updated on 10-Nov-2020 08:17:11