Open In App

Find the winner of a game of removing any number of stones from the least indexed non-empty pile from given N piles

Last Updated : 17 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers, each representing size of a pile of stones. The task is to determine the winner of the game when two players, A and B, play a game optimally as per the following conditions:

  • Player A always starts the game.
  • In one move, a player may remove any number of stones (at least 1), from the first non-empty pile with minimal index.
  • The first player who cannot make a move loses the game.

Print “A” if player A wins the game. Otherwise, print “B”.

Examples:

Input: arr[] = {1, 1, 1, 1, 1, 1}
Output: B
Explanation:
Here, each pile has only one stone so A and B will alternatively remove one stone each.
A removes 1 stone from 1st pile, B removes 1 from 2nd pile and so on.
Last stone in 6th pile is removed by B.
Since A has no choice left, B wins the game.

Input: arr[] = {1, 1, 2, 1}
Output: A
Explanation:
Here, 
A removes 1 stone from 1st pile, 
B removes 1 from 2nd pile, 
A removes only 1 from 3rd pile, 
and now B is forced to remove 1 from 3rd pile. 
Last stone in 4th pile is removed by A.
Since B has no choice left, A wins the game.

Approach: The idea is to figure out the optimal ways that players should follow to win the game. Below are two ways to play optimally:

  • For all piles except the last one, if there are K stones on a pile then the current player will pick only (K – 1) stones (only if K > 1) so that another player is forced to pick the remaining 1 stone. This guarantees the current player to get a chance to pick stones from the next pile and eventually win.
  • For the last pile, if it has K stones, then all K stones will be picked by the current player so that the other player does not get a chance to pick stones. This eventually guarantees the current player to win.

Follow the steps below to solve this problem:

  1. Initially, assuming that the player will remove all stones from the current pile, A will be the winner if the size of the array is odd and B if the size is even.
  2. Now, iterate over the range [0, N – 2] and check the current index and number of stones present on the current pile to decide which player will win.
  3. While traversing, if the index is even, A will get a chance to pick a stone. Otherwise, B will get a chance to pick stones.
  4. If the current index is even and the number of stones is greater than 1, then the winner is set to B. Update winner to A.
  5. If the current index is odd and the number of stones exceeds 1, the winner is set to be A. Then, update the winner to B.
  6. Finally, print the winner of the game.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the winner
// of game between A and B
void findWinner(int a[], int n)
{
    // win = 1 means B is winner
    // win = 0 means A is winner
    int win = 0;
 
    // If size is even, winner is B
    if (n % 2 == 0)
        win = 1;
 
    // If size is odd, winner is A
    else
        win = 0;
 
    for (int i = n - 2; i >= 0; i--) {
 
        // Stone will be removed by B
        if (i % 2 == 1) {
 
            // If B wants to win
 
            // B will take n-1 stones
            // from current pile having
            // n stones and force A to
            // pick 1 stone
            if (win == 0 && a[i] > 1)
                win = 1;
        }
 
        // Stone will be removed by A
        else {
 
            // If A wants to win
 
            // A will take n-1 stones from
            // current pile having n stones
            // and force B to pick 1 stone
            if (win == 1 && a[i] > 1)
                win = 0;
        }
    }
 
    // Print the winner accordingly
    if (win == 0)
        cout << "A";
    else
        cout << "B";
}
 
// Driver Code
int main()
{
    // Given piles of stone
    int arr[] = { 1, 1, 1, 2 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    findWinner(arr, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the winner
// of game between A and B
static void findWinner(int a[], int n)
{
     
    // win = 1 means B is winner
    // win = 0 means A is winner
    int win = 0;
 
    // If size is even, winner is B
    if (n % 2 == 0)
        win = 1;
 
    // If size is odd, winner is A
    else
        win = 0;
 
    for(int i = n - 2; i >= 0; i--)
    {
         
        // Stone will be removed by B
        if (i % 2 == 1)
        {
             
            // If B wants to win
 
            // B will take n-1 stones
            // from current pile having
            // n stones and force A to
            // pick 1 stone
            if (win == 0 && a[i] > 1)
                win = 1;
        }
 
        // Stone will be removed by A
        else
        {
             
            // If A wants to win
 
            // A will take n-1 stones from
            // current pile having n stones
            // and force B to pick 1 stone
            if (win == 1 && a[i] > 1)
                win = 0;
        }
    }
 
    // Print the winner accordingly
    if (win == 0)
        System.out.print("A");
    else
        System.out.print("B");
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given piles of stone
    int arr[] = { 1, 1, 1, 2 };
 
    int N = arr.length;
 
    // Function call
    findWinner(arr, N);
}
}
 
// This code is contributed by Amit Katiyar


Python3




# Python3 program for the above approach
 
# Function to find the winner
# of game between A and B
def findWinner(a, n):
     
    # win = 1 means B is winner
    # win = 0 means A is winner
    win = 0
 
    # If size is even, winner is B
    if (n % 2 == 0):
        win = 1
 
    # If size is odd, winner is A
    else:
        win = 0
 
    for i in range(n - 2, -1, -1):
 
        # Stone will be removed by B
        if (i % 2 == 1):
 
            # If B wants to win
 
            # B will take n-1 stones
            # from current pile having
            # n stones and force A to
            # pick 1 stone
            if (win == 0 and a[i] > 1):
                win = 1
 
        # Stone will be removed by A
        else:
 
            # If A wants to win
 
            # A will take n-1 stones from
            # current pile having n stones
            # and force B to pick 1 stone
            if (win == 1 and a[i] > 1):
                win = 0
                 
    # Print the winner accordingly
    if (win == 0):
        print("A")
    else:
        print("B")
 
# Driver Code
if __name__ == '__main__':
     
    # Given piles of stone
    arr = [ 1, 1, 1, 2 ]
 
    N = len(arr)
 
    # Function call
    findWinner(arr, N)
 
# This code is contributed by mohit kumar 29


C#




// C# program for the
// above approach
using System;
class GFG{
 
// Function to find the winner
// of game between A and B
static void findWinner(int []a,
                       int n)
{   
  // win = 1 means B is winner
  // win = 0 means A is winner
  int win = 0;
 
  // If size is even, winner is B
  if (n % 2 == 0)
    win = 1;
 
  // If size is odd, winner is A
  else
    win = 0;
 
  for(int i = n - 2; i >= 0; i--)
  {
    // Stone will be removed by B
    if (i % 2 == 1)
    {
 
      // If B wants to win
 
      // B will take n-1 stones
      // from current pile having
      // n stones and force A to
      // pick 1 stone
      if (win == 0 && a[i] > 1)
        win = 1;
    }
 
    // Stone will be removed by A
    else
    {
      // If A wants to win
      // A will take n-1 stones from
      // current pile having n stones
      // and force B to pick 1 stone
      if (win == 1 && a[i] > 1)
        win = 0;
    }
  }
 
  // Print the winner accordingly
  if (win == 0)
    Console.Write("A");
  else
    Console.Write("B");
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given piles of stone
  int []arr = {1, 1, 1, 2};
 
  int N = arr.Length;
 
  // Function call
  findWinner(arr, N);
}
}
 
 // This code is contributed by Rajput-Ji


Javascript




<script>
// Javascript program for the above approach
 
// Function to find the winner
// of game between A and B
function findWinner(a, n)
{
 
    // win = 1 means B is winner
    // win = 0 means A is winner
    let win = 0;
  
    // If size is even, winner is B
    if (n % 2 == 0)
        win = 1;
  
    // If size is odd, winner is A
    else
        win = 0;
  
    for(let i = n - 2; i >= 0; i--)
    {
          
        // Stone will be removed by B
        if (i % 2 == 1)
        {
              
            // If B wants to win
  
            // B will take n-1 stones
            // from current pile having
            // n stones and force A to
            // pick 1 stone
            if (win == 0 && a[i] > 1)
                win = 1;
        }
  
        // Stone will be removed by A
        else
        {
              
            // If A wants to win
  
            // A will take n-1 stones from
            // current pile having n stones
            // and force B to pick 1 stone
            if (win == 1 && a[i] > 1)
                win = 0;
        }
    }
  
    // Print the winner accordingly
    if (win == 0)
        document.write("A");
    else
        document.write("B");
}
 
// Driver Code
// Given piles of stone
let arr=[1, 1, 1, 2];
let N = arr.length;
 
// Function call
findWinner(arr, N);
 
// This code is contributed by unknown2108
</script>


Output: 

B

Time Complexity: O(N)
Auxiliary Space: O(1)



Similar Reads

Find the winner of a game of removing at most 3 stones from a pile in each turn
Given an array arr[] of size N, denoting values assigned to N stones, two players, Player1 and Player2, play a game of alternating turns. In each turn, a player can take 1, 2, or 3 stones from the first remaining stones with the sum of values of all the removed stones added to the player's score. Considering that both players play optimally, the ta
22 min read
Check if two piles of coins can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other
Given two piles of coins consisting of N and M coins, the task is to check if both the piles can be emptied simultaneously by repeatedly removing 2 coins from one pile and 1 coin from the other pile. If both the piles can be made empty, then print "Yes". Otherwise, print "No". Examples: Input: N = 1, M = 2 Output: Yes Explanation: Remove 1 coin fro
6 min read
Predict the winner of a card game of removing K cards in each turn such that Bitwise AND of K and size of pile is 0
There are two players A and B and a pile of N cards stacked upon each other. The task is to find the winner of the game, assuming both players play optimally as per the following guidelines: Player A always begins the game and the players take alternate turns subsequently.In each turn, a player can remove K( 1 ? K ? N) cards if K &amp; n = 0, where
8 min read
Find the winner of the game with N piles of boxes
Given N piles containing White(W) and Black(B) boxes only, two players A and B play a game. Player A may remove any number of boxes from the top of the pile having the topmost box White, and Player B may remove any number of boxes from the top of the pile having the topmost box Black. If there is a pile with top as W, then player A has removed one
6 min read
Find the winner of game of repeatedly removing the first character to empty given string
Given a positive integer N, representing the count of players playing the game and an array of strings arr[], consisting of the numeric strings made up of digits from the range ['1', 'N']. Considering ith player is assigned with the string arr[i], the task is to find the winner of the game when all N players play the game optimally as per the follo
7 min read
Find the player with least 0s after emptying a Binary String by removing non-empty substrings
Given a binary string S, the task is to determine the winner of the game when two players play a game optimally in alternate turns with the given string, as per the following conditions: Player 1 always starts first.In each turn, a player removes a non-empty substring from the given string.After the given string is emptied, the player having the mi
7 min read
Minimum number of coins to be collected per hour to empty N piles in at most H hours
Given an array arr[] consisting of N integers representing the number of coins in each pile, and an integer H, the task is to find the minimum number of coins that must be collected from a single pile per hour such that all the piles are emptied in less than H hours. Note: Coins can be collected only from a single pile in an hour. Examples: Input:
8 min read
Find the winner of the Game of removing odd or replacing even array elements
Given an array arr[] consisting of N integers. Two players, Player 1 and Player 2, play turn-by-turn in which one player can may either of the following two moves: Convert even array element to any other integer.Remove odd array element. The player who is not able to make any move loses the game. The task is to print the winner of the game. Print -
7 min read
Find the winner of game of removing array elements having GCD equal to 1
Given an array arr[] of size N, the task is to find the winner of the game when two players play the game optimally as per the following rules: Player 1 starts the game.In each turn, a player removes an element from the array.Player 2 will win the game only if GCD of all the elements removed by Player 1 becomes equal to 1. Examples: Input: arr[] =
10 min read
Find the winner of the Game to Win by erasing any two consecutive similar alphabets
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. Examples: Input: str = "kaak" Output: B Explanation:
5 min read
Article Tags :
Practice Tags :