Given a string consisting of lower case alphabets.
Rules of the Game:
- A player can choose a pair of similar consecutive characters and erase them.
- There are two players playing the game, the player who makes the last move wins.
The task is to find the winner if A goes first and both play optimally.
Input: str = "kaak" Output: B Explanation: Initial String: "kaak" A's turn: removes: "aa" Remaining String: "kk" B's turn: removes: "kk" Remaining String: "" Since B was the last one to play B is the winner. Input: str = "kk" Output: A
Approach: We can use a stack to simplify the problem.
- Each time we encounter a character that is different from the one present in the top of the stack we add it to the stack.
- If the stack top and the next character match we pop the character from the stack and increment the count.
- At the end, we just need to see who wins by checking count%2.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if any K ranges overlap at any point
- Delete consecutive same words in a sequence
- Check if stack elements are pairwise consecutive
- Check if Queue Elements are pairwise consecutive
- Reduce the string by removing K consecutive identical characters
- Implement two stacks in an array
- Iterative Postorder Traversal | Set 1 (Using Two Stacks)
- Check if two trees are Mirror
- Bubble sort using two Stacks
- Check if two expressions with brackets are same
- Level order traversal with direction change after every two levels
- Merging and Sorting Two Unsorted Stacks
- Infix to Prefix conversion using two stacks
- Check if concatenation of two strings is balanced or not
- Add two numbers represented by Stacks
- Check if the two given stacks are same
- Nodes from given two BSTs with sum equal to X
- Find the nearest smaller numbers on left side in an array
- Find maximum of minimum for every window size in a given array
- Find if an expression has duplicate parenthesis or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.