Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find the winner in nim-game
Next article icon

Find winner in the game of Binary Array

Last Updated : 28 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary array X[] of size N. Two players A and B are playing games having the following rules, then the task is to determine the winner if B starts first and both players play optimally. The rules are:

  • In the first turn, a player selects any index i (1 ≤ i ≤ N) such that A[i] = 0.
  • After their first move, a player can choose an index, which is just adjacent to the previously selected index, and the element at that index is also 0.
  • After selecting any index, The element is changed to 1 in X[].
  • The player which can't make any move loses the game.

Examples:

Input: N = 7, X[] = {1, 0, 1, 1, 1, 0, 0} 
Output: A
Explanation: The moves of the games by both players are as follows:

  • Player B: Selects A[ 7 ] = 0. Now update A[ 7 ] = 1.
  • Player A: Selects A[ 6 ] = 0. Now update A[ 6 ] = 1.

Now, player B can''t make any move because there is no adjacent index,  such that the element at that index is equal to 0. 

Input: N = 8, X[] = {1, 1, 0, 0, 0, 0, 0, 1}
Output: B
Explanation: The moves of the game are as follows:

  • Player B: Selects A[5]=0. Now update A[5]=1.
  • Player A: Selects A[4]=0. Now update A[4]=1.
  • Player B: Selects A[6]=0. Now update A[6]=1.
  • Player A: Selects A[3]=0. Now update A[3]=1.
  • Player B: Selects A[7]=0. Now update A[7]=1.

Now, player A can't make any move because there is no adjacent index, such that the element at that index is equal to 0.

Approach: The problem is based on the Greedy approach.

Iterate through the array a[] and calculate the maximum frequency of consecutive zeros seen so far and store in variable maxc1 and calculate the second maximum frequency of consecutive zeros seen so far and store in variable maxc2. Now check if the maximum frequency maxc1 is odd and the second maximum frequency maxc2 is strictly less than (maxc1+1)/2, player "B" wins, else player "A" wins.

Steps were taken to solve the problem:

  • Count the Number of Consecutive zeros in the array.
  • Iterate through the array X[] and count the maximum frequency of consecutive zeros and the second maximum frequency of consecutive zeros and store them in maxc1 and maxc2 respectively.
  • Check if the last element of X[] is zero and update the maximum frequency variables if necessary.
  • Check if maxc1 is odd and maxc2 is strictly less than (maxc1+1)/2, player "B" wins, else player "A" wins.

Below is the code to implement the approach:

C++14
// C++ code for the above approach: #include <bits/stdc++.h> using namespace std;  // Function to find winner string findWinner(int n, int a[]) {      int count = 0;     int maxc1 = 0, maxc2 = 0;      for (int i = 0; i < n; i++) {         if (a[i]) {             if (count > maxc2) {                 maxc2 = count;                 if (count > maxc1) {                     maxc2 = maxc1;                     maxc1 = count;                 }             }             count = 0;         }         else {             count++;         }     }      if (a[n - 1] == 0) {         if (count > maxc2) {             maxc2 = count;             if (count > maxc1) {                 maxc2 = maxc1;                 maxc1 = count;             }         }     }      if ((maxc1 & 1) and (maxc2 < (maxc1 + 1) / 2)) {         return "A";     }     else {         return "B";     } }  // Drivers code int main() {      int n = 8;     int a[8] = { 1, 1, 0, 0, 0, 0, 0, 1 };      // Function call     cout << findWinner(n, a);      return 0; } 
Java
import java.util.Arrays;  public class GFG {       // Function to find winner     public static String findWinner(int n, int[] a) {         int count = 0;         int maxc1 = 0, maxc2 = 0;         for (int i = 0; i < n; i++) {             if (a[i] != 0) {                 if (count > maxc2) {                       // Update the second maximum count                     maxc2 = count;                     if (count > maxc1) {                           // Update the maximum count                             maxc2 = maxc1;                         maxc1 = count;                     }                 }                 count = 0;             } else {                   // Increment the count of consecutive zeros                 count++;             }         }         if (a[n - 1] == 0) {             if (count > maxc2) {                   // Update the second maximum count                 maxc2 = count;                 if (count > maxc1) {                       // Update the maximum count                     maxc2 = maxc1;                     maxc1 = count;                 }             }         }                  // Check the conditions and return the winner         if ((maxc1 & 1) != 0 && (maxc2 < (maxc1 + 1) / 2)) {             return "A";         } else {             return "B";         }     }      public static void main(String[] args) {         int n = 8;         int[] a = { 1, 1, 0, 0, 0, 0, 0, 1 };            // Function call         System.out.println(findWinner(n, a));     } } 
Python3
#  Function to find winner def findWinner(n, a):     count = 0     maxc1 = 0     maxc2 = 0     for i in range(n):         if a[i]:             if count > maxc2:                 maxc2 = count                 if count > maxc1:                     maxc2 = maxc1                     maxc1 = count             count = 0         else:             count += 1     if a[n - 1] == 0:         if count > maxc2:             maxc2 = count             if count > maxc1:                 maxc2 = maxc1                 maxc1 = count     if (maxc1 & 1) and (maxc2 < (maxc1 + 1) // 2):         return "A"     else:         return "B"  n = 8 a = [1, 1, 0, 0, 0, 0, 0, 1] # Function call print(findWinner(n, a)) 
C#
// C# code for the above approach:  using System;  class GFG {     static string FindWinner(int n, int[] a)     {         int count = 0;         int maxc1 = 0, maxc2 = 0;          for (int i = 0; i < n; i++)         {             if (a[i] == 1)             {                 if (count > maxc2)                 {                     // Update the second maximum count                     maxc2 = count;                      if (count > maxc1)                     {                         // Update the maximum count                         maxc2 = maxc1;                         maxc1 = count;                     }                 }                 count = 0;             }             else             {                 // Increment the count of consecutive zeros                 count++;             }         }          if (a[n - 1] == 0)         {             if (count > maxc2)             {                 // Update the second maximum count                 maxc2 = count;                  if (count > maxc1)                 {                     // Update the maximum count                     maxc2 = maxc1;                     maxc1 = count;                 }             }         }          // Check the conditions and return the winner         if ((maxc1 % 2 != 0) || (maxc2 < (maxc1 + 1) / 2))         {             return "A";         }         else         {             return "B";         }     }      static void Main()     {         int n = 8;         int[] a = { 1, 1, 0, 0, 0, 0, 0, 1 };          // Function call         Console.WriteLine(FindWinner(n, a));     } } 
JavaScript
// Function to find winner const findWinner = (n, a) => {     let count = 0;     let maxc1 = 0;     let maxc2 = 0;     for (let i = 0; i < n; i++) {         if (a[i]) {             if (count > maxc2) {                 maxc2 = count;                 if (count > maxc1) {                     maxc2 = maxc1;                     maxc1 = count;                 }             }             count = 0;         } else {             count += 1;         }     }     if (a[n - 1] === 0) {         if (count > maxc2) {             maxc2 = count;             if (count > maxc1) {                 maxc2 = maxc1;                 maxc1 = count;             }         }     }     if ((maxc1 & 1) && (maxc2 < (maxc1 + 1) / 2)) {         return "A";     } else {         return "B";     } };  const n = 8; const a = [1, 1, 0, 0, 0, 0, 0, 1]; // Function call console.log(findWinner(n, a)); 

Output
A

Time Complexity: O(N)
Auxiliary Space: O(N), As a vector is used to store adjacent frequencies of zeros.


Next Article
Find the winner in nim-game
author
gatecoders83172
Improve
Article Tags :
  • Greedy
  • Competitive Programming
  • DSA
  • Arrays
  • Algorithms-Greedy Algorithms
  • Greedy Algorithms
  • Java-Competitive-Programming
Practice Tags :
  • Arrays
  • Greedy

Similar Reads

  • Find the winner in game of rotated Array
    Given a circular connected binary array X[] of length N. Considered two players A and B are playing the game on the following move: Choose a sub-array and left-rotate it once. The move is said to be valid if and only if the number of adjacent indices in X[] having different values (after rotation) i
    8 min read
  • Find the winner in nim-game
    You are given an array A[] of n-elements. There are two players Alice and Bob. A Player can choose any of element from array and remove it. If the bitwise XOR of all remaining elements equals 0 after removal of selected element, then that player loses. This problem is variation of nim-game. Note: Ea
    7 min read
  • Find the transition point in a binary array
    Given a sorted array, arr[], containing only 0s and 1s, find the transition point, i.e., the first index where 1 was observed, and before that, only 0 was observed. If arr does not have any 1, return -1. If the array does not have any 0, return 0. Examples : Input: 0 0 0 1 1Output: 3Explanation: Ind
    7 min read
  • Find the winner of the Game
    Given an array arr[] of N integers and two players A and B are playing a game where the players pick the element with the maximum digit sum in their turns. In the end, the player with the maximum sum of the picked elements wins the game. Assuming that player A always starts the game first and both t
    7 min read
  • Determine winner of the Game by arranging balls in a row
    Given the number of small and large balls N and M respectively, the task is to find which player wins if both the player X and Y play optimally by making the following two moves: Player X will try to keep the same type of ball i.e., small followed by another small ball or large ball is followed by a
    7 min read
  • Find Winner of Flip Game II
    Given a string currentState that contains only '+' and '-'. You and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move. The task is to return true if the starting player can guarantee a win, and false otherwise. Examples: Input: s = "
    7 min read
  • Find the winner of a game of donating i candies in every i-th move
    Given two integers X and Y representing the number of candies allocated to players A and B respectively, where both the players indulge in a game of donating i candies to the opponent in every ith move. Starting with player A, the game continues with alternate turns until a player is unable to donat
    6 min read
  • Find winner of the game when any set bit is removed in each move
    Two players, Player 1 and Player 2, are given an integer N to play a game. The rules of the game are as follows : In one turn, a player can remove any set bit of N in its binary representation to make a new N. Player 1 always takes the first turn. If a player cannot make a move, he loses.Examples: I
    8 min read
  • Find the winner of the game based on the given moves
    Given two integers N and M. Two players A and B are playing this game, and the task is to find the winner A or B according to the given moves if both players play the game optimally and A starts first. The move of the games are as follows: The player destroys anyone from both integers and then divid
    4 min read
  • Find winner of the Game where Array elements are reduced in each turn
    Given a circular array arr[] of size N containing positive integers only, Player A and B are playing a game, turn by turn, the game will start with player A at index 0 and then player B at the next index. In every turn a player can deduct some value from arr[i] and decrease the value of an element a
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences