Open In App

Find the last player to be able to remove a string from an array which is not already removed from other array

Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays of strings arr[] and brr[] of size N and M respectively, 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.
  • Player 1 removes a string from the array arr[] if it is not already removed from the array brr[].
  • Player 2 removes a string from the array brr[] if it is not already removed from the array arr[].
  • The player who is not able to remove a string from the array, then the player will lose the game.

Examples:

Input: arr[] = { “geeks”, “geek” }, brr[] = { “geeks”, “geeksforgeeks” } 
Output: Player 1 
Explanation: 
Turn 1: Player 1 removed “geeks” from arr[]. 
Turn 2: Player 2 removed “geeksforgeeks” from brr[] 
Turn 3: Player 1 removed “geek” from brr[]. 
Now, player 2 cannot remove any string. 
Therefore, the required output is Player 1.

Input: arr[] = { “a”, “b” }, brr[] = { “a”, “b” } 
Output: Player 2 
Explanation: 
Turn 1: Player 1 removed “a” from arr[]. 
Turn 2: Player 2 removed “b” from brr[]. 
Therefore, the required output is Player 2

Approach: The idea to based on the fact that common strings from both the arrays can be removed only from one of the arrays. Follow the steps below to solve the problem:

  • If the count of common strings from both the arrays is an odd number, then remove one string from the array brr[], as Player 1 starts the game and the first common string is removed by Player 1.
  • If count of strings in arr[] is greater than the count of strings in brr[] by removing the common strings from both the arrays, then print “Player 1”.
  • Otherwise, print “Player 2”.

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 last player to be
// able to remove a string from one array
// which has not been removed from the other array
void lastPlayer(int n, int m, vector<string> arr,
                       vector<string> brr)
{
 
    // Stores common strings
    // from both the array
   set<string> common;
 
    for (int i = 0; i < arr.size(); i++)
    {
        for (int j = 0; j < brr.size(); j++)
        {
            if (arr[i] == brr[j])
            {
 
                // add common elements
                common.insert(arr[i]);
                break;
            }
        }
    }
 
    // Removing common strings from arr[]
    set<string> a;
    bool flag;
    for (int i = 0; i < arr.size(); i++)
    {
        flag = false;
        for (auto value : common)
        {
            if (value == arr[i])
            {
 
                // add common elements
                flag = true;
                break;
            }
        }
        if (flag)
            a.insert(arr[i]);
    }
 
    // Removing common elements from B
    set<string> b;
    for (int i = 0; i < brr.size(); i++)
    {
        flag = false;
        for (auto value : common)
        {
            if (value == brr[i])
            {
 
                // add common elements
                flag = true;
                break;
            }
        }
 
        if (flag)
            b.insert(brr[i]);
    }
 
    // Stores strings in brr[] which
    // is not common in arr[]
    int LenBrr = b.size();
    if ((common.size()) % 2 == 1)
    {
 
        // Update LenBrr
        LenBrr -= 1;
    }
 
    if (a.size() > LenBrr)
    {
        cout<<("Player 1")<<endl;
    }
    else
    {
        cout<<("Player 2")<<endl;
    }
}
 
// Driver Code
int main()
{
   
    // Set of strings for player A
    vector<string> arr{ "geeks", "geek" };
 
    // Set of strings for player B
    vector<string> brr{ "geeks", "geeksforgeeks" };
    int n = arr.size();
    int m = brr.size();
    lastPlayer(n, m, arr, brr);
}
 
// This code is contributed by SURENDRA_GANGWAR.


Java




// Java Program for the above approach
import java.io.*;
import java.util.*;
class GFG
{
    // Function to find last player to be
    // able to remove a string from one array
    // which has not been removed from the other array
    static void lastPlayer(int n, int m, String[] arr,
                           String[] brr)
    {
 
        // Stores common strings
        // from both the array
        Set<String> common = new HashSet<>();
 
        for (int i = 0; i < arr.length; i++)
        {
            for (int j = 0; j < brr.length; j++)
            {
                if (arr[i] == brr[j])
                {
 
                    // add common elements
                    common.add(arr[i]);
                    break;
                }
            }
        }
 
        // Removing common strings from arr[]
        Set<String> a = new HashSet<>();
        boolean flag;
        for (int i = 0; i < arr.length; i++)
        {
            flag = false;
            for (String value : common)
            {
                if (value == arr[i])
                {
 
                    // add common elements
                    flag = true;
                    break;
                }
            }
            if (flag)
                a.add(arr[i]);
        }
 
        // Removing common elements from B
        Set<String> b = new HashSet<>();
        for (int i = 0; i < brr.length; i++)
        {
            flag = false;
            for (String value : common)
            {
                if (value == brr[i])
                {
 
                    // add common elements
                    flag = true;
                    break;
                }
            }
 
            if (flag)
                b.add(brr[i]);
        }
 
        // Stores strings in brr[] which
        // is not common in arr[]
        int LenBrr = b.size();
        if ((common.size()) % 2 == 1)
        {
 
            // Update LenBrr
            LenBrr -= 1;
        }
 
        if (a.size() > LenBrr)
        {
            System.out.print("Player 1");
        }
        else
        {
            System.out.print("Player 2");
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
       
        // Set of strings for player A
        String[] arr = { "geeks", "geek" };
 
        // Set of strings for player B
        String[] brr = { "geeks", "geeksforgeeks" };
        int n = arr.length;
        int m = brr.length;
        lastPlayer(n, m, arr, brr);
    }
}
 
// This code is contributed by Dharanendra L V.


Python




# Python Program for the above approach
 
 
# Function to find last player to be
# able to remove a string from one array
# which has not been removed from the other array
def lastPlayer(n, m, arr, brr):
 
    # Stores common strings
    # from both the array
    common = list(set(arr) & set(brr))
 
    # Removing common strings from arr[]
    a = list(set(arr) ^ set(common))
 
    # Removing common elements from B
    b = list(set(brr) ^ set(common))
 
    # Stores strings in brr[] which
    # is not common in arr[]
    LenBrr = len(b)
 
    if len(common) % 2 == 1:
 
        # Update LenBrr
        LenBrr -= 1
     
    if len(a) > LenBrr:
        print("Player 1")
    else:
        print("Player 2")
 
 
# Driver Code
if __name__ == '__main__':
 
    # Set of strings for player A
    arr = ["geeks", "geek"]
 
    # Set of strings for player B
    brr = ["geeks", "geeksforgeeks"]
     
    n = len(arr)
    m = len(brr)
 
    lastPlayer(n, m, arr, brr)


C#




// C# Program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
   
    // Function to find last player to be
    // able to remove a string from one array
    // which has not been removed from the other array
    static void lastPlayer(int n, int m, String[] arr,
                           String[] brr)
    {
 
        // Stores common strings
        // from both the array
        HashSet<String> common = new HashSet<String>();
        for (int i = 0; i < arr.Length; i++)
        {
            for (int j = 0; j < brr.Length; j++)
            {
                if (arr[i] == brr[j])
                {
 
                    // add common elements
                    common.Add(arr[i]);
                    break;
                }
            }
        }
 
        // Removing common strings from []arr
        HashSet<String> a = new HashSet<String>();
        bool flag;
        for (int i = 0; i < arr.Length; i++)
        {
            flag = false;
            foreach (String value in common)
            {
                if (value == arr[i])
                {
 
                    // add common elements
                    flag = true;
                    break;
                }
            }
            if (flag)
                a.Add(arr[i]);
        }
 
        // Removing common elements from B
        HashSet<String> b = new HashSet<String>();
        for (int i = 0; i < brr.Length; i++)
        {
            flag = false;
            foreach (String value in common)
            {
                if (value == brr[i])
                {
 
                    // add common elements
                    flag = true;
                    break;
                }
            }
 
            if (flag)
                b.Add(brr[i]);
        }
 
        // Stores strings in brr[] which
        // is not common in []arr
        int LenBrr = b.Count;
        if ((common.Count) % 2 == 1)
        {
 
            // Update LenBrr
            LenBrr -= 1;
        }
 
        if (a.Count > LenBrr)
        {
            Console.Write("Player 1");
        }
        else
        {
            Console.Write("Player 2");
        }
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
       
        // Set of strings for player A
        String[] arr = { "geeks", "geek" };
 
        // Set of strings for player B
        String[] brr = { "geeks", "geeksforgeeks" };
        int n = arr.Length;
        int m = brr.Length;
        lastPlayer(n, m, arr, brr);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
      // JavaScript Program for the above approach
      // Function to find last player to be
      // able to remove a string from one array
      // which has not been removed from the other array
      function lastPlayer(n, m, arr, brr)
      {
       
        // Stores common strings
        // from both the array
        var common = [];
        for (var i = 0; i < arr.length; i++)
        {
          for (var j = 0; j < brr.length; j++)
          {
            if (arr[i] === brr[j])
            {
             
              // add common elements
              common.push(arr[i]);
              j = brr.length;
            }
          }
        }
 
        // Removing common strings from []arr
        var a = [];
        var flag;
        for (var i = 0; i < arr.length; i++) {
          flag = false;
          common.forEach((value) => {
            if (value === arr[i])
            {
             
              // add common elements
              flag = true;
              i = arr.length;
            }
          });
          if (flag) a.push(arr[i]);
        }
 
        // Removing common elements from B
        var b = [];
        for (var i = 0; i < brr.length; i++) {
          flag = false;
          common.forEach((value) => {
            if (value === brr[i]) {
              // add common elements
              flag = true;
              i = brr.length;
            }
          });
 
          if (flag) b.push(brr[i]);
        }
 
        // Stores strings in brr[] which
        // is not common in []arr
        var LenBrr = b.length;
        if (common.length % 2 === 1) {
          // Update LenBrr
          LenBrr -= 1;
        }
 
        if (a.length > LenBrr) {
          document.write("Player 1");
        } else {
          document.write("Player 2");
        }
      }
 
      // Driver Code
      // Set of strings for player A
      var arr = ["geeks", "geek"];
 
      // Set of strings for player B
      var brr = ["geeks", "geeksforgeeks"];
      var n = arr.length;
      var m = brr.length;
      lastPlayer(n, m, arr, brr);
       
      // This code is contributed by rdtank.
    </script>


Output

Player 1







Time Complexity: O(N + M)
Auxiliary Space: O(N + M)

 Using Hash Map:

Approach:

In this approach, we can use a hash map to keep track of the removed strings in both arrays. Each time a player removes a string from one of the arrays, we mark that string as removed in the hash map. Then, we check if any string in the other array is still available to be removed. If there is no available string, the last player to remove a string wins.

Initialize an empty dictionary to keep track of the removed strings in both arrays.
Initialize a variable ‘turn’ to 1, to keep track of which player’s turn it is.
While at least one of the arrays is not empty, do the following:
If it is player 1’s turn and array ‘arr’ is not empty, remove the first string from ‘arr’ and mark it as removed in the dictionary.
If it is player 2’s turn and array ‘brr’ is not empty, remove the first string from ‘brr’ and mark it as removed in the dictionary.
Switch turns by setting ‘turn’ to 3 – ‘turn’.
Check if there are any strings left in the other array that have not been removed yet.
If there are no available strings, return the current player’s turn as the winner.
If both arrays are empty and no winner has been found, return -1 as an error code.

C++




// C++ code for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
int findLastPlayer(vector<string>& arr, vector<string>& brr)
{
    unordered_map<string, bool> removed;
    int turn = 1;
 
    while (!arr.empty() || !brr.empty()) {
        if (turn == 1) {
            if (arr.empty()) {
                return 2;
            }
            string toRemove = arr[0];
            removed[toRemove] = true;
            arr.erase(arr.begin());
        }
        else {
            if (brr.empty()) {
                return 1;
            }
            string toRemove = brr[0];
            removed[toRemove] = true;
            brr.erase(brr.begin());
        }
 
        turn = 3 - turn;
 
        bool foundInArr = false;
        for (string& s : arr) {
            if (removed.find(s) == removed.end()) {
                foundInArr = true;
                break;
            }
        }
 
        if (!foundInArr) {
            for (string& s : brr) {
                if (removed.find(s) == removed.end()) {
                    return 1;
                }
            }
            return 2; // If both arr and brr are empty,
                      // return 2
        }
    }
 
    return -1; // should never reach this point
}
 
int main()
{
    vector<string> arr1 = { "geeks", "geek" };
    vector<string> brr1 = { "geeks", "geeksforgeeks" };
    cout << findLastPlayer(arr1, brr1)
         << endl; // should print 1
 
    vector<string> arr2 = { "a", "b" };
    vector<string> brr2 = { "a", "b" };
    cout << findLastPlayer(arr2, brr2)
         << endl; // should print 2
 
    return 0;
}
 
// This code is contributed by Abhinav Mahajan (abhinav_m22)


Java




import java.util.ArrayList;
import java.util.HashMap;
 
public class LastPlayerFinder {
    static int findLastPlayer(ArrayList<String> arr, ArrayList<String> brr) {
        HashMap<String, Boolean> removed = new HashMap<>();
        int turn = 1;
 
        while (!arr.isEmpty() || !brr.isEmpty()) {
            if (turn == 1) {
                if (arr.isEmpty()) {
                    return 2;
                }
                String toRemove = arr.remove(0);
                removed.put(toRemove, true);
            } else {
                if (brr.isEmpty()) {
                    return 1;
                }
                String toRemove = brr.remove(0);
                removed.put(toRemove, true);
            }
 
            turn = 3 - turn;
 
            boolean foundInArr = false;
            for (String s : arr) {
                if (!removed.containsKey(s)) {
                    foundInArr = true;
                    break;
                }
            }
 
            if (!foundInArr) {
                for (String s : brr) {
                    if (!removed.containsKey(s)) {
                        return 1;
                    }
                }
                return 2; // If both arr and brr are empty, return 2
            }
        }
 
        return -1; // should never reach this point
    }
 
    public static void main(String[] args) {
        ArrayList<String> arr1 = new ArrayList<>();
        arr1.add("geeks");
        arr1.add("geek");
        ArrayList<String> brr1 = new ArrayList<>();
        brr1.add("geeks");
        brr1.add("geeksforgeeks");
        System.out.println(findLastPlayer(arr1, brr1)); // should print 1
 
        ArrayList<String> arr2 = new ArrayList<>();
        arr2.add("a");
        arr2.add("b");
        ArrayList<String> brr2 = new ArrayList<>();
        brr2.add("a");
        brr2.add("b");
        System.out.println(findLastPlayer(arr2, brr2)); // should print 2
    }
}


Python3




def find_last_player(arr, brr):
    removed = {}
    turn = 1
    while len(arr) > 0 or len(brr) > 0:
        if turn == 1:
            if len(arr) == 0:
                return 2
            to_remove = arr.pop(0)
            removed[to_remove] = True
        else:
            if len(brr) == 0:
                return 1
            to_remove = brr.pop(0)
            removed[to_remove] = True
        turn = 3 - turn
        for i in range(len(arr)):
            if arr[i] not in removed:
                break
        else:
            for i in range(len(brr)):
                if brr[i] not in removed:
                    break
            else:
                return turn
    return -1 # should never reach this point
arr = ["geeks", "geek"]
brr = ["geeks", "geeksforgeeks"]
print(find_last_player(arr, brr)) # should print 1
arr = ["a", "b"]
brr = ["a", "b"]
print(find_last_player(arr, brr)) # should print 2


C#




using System;
using System.Collections.Generic;
 
class Program
{
    static int FindLastPlayer(List<string> arr, List<string> brr)
    {
        Dictionary<string, bool> removed = new Dictionary<string, bool>();
        int turn = 1;
 
        while (arr.Count > 0 || brr.Count > 0)
        {
            if (turn == 1)
            {
                if (arr.Count == 0)
                {
                    return 2;
                }
                string toRemove = arr[0];
                removed[toRemove] = true;
                arr.RemoveAt(0);
            }
            else
            {
                if (brr.Count == 0)
                {
                    return 1;
                }
                string toRemove = brr[0];
                removed[toRemove] = true;
                brr.RemoveAt(0);
            }
 
            turn = 3 - turn;
 
            bool foundInArr = false;
            foreach (string s in arr)
            {
                if (!removed.ContainsKey(s))
                {
                    foundInArr = true;
                    break;
                }
            }
 
            if (!foundInArr)
            {
                foreach (string s in brr)
                {
                    if (!removed.ContainsKey(s))
                    {
                        return 1;
                    }
                }
                return 2; // If both arr and brr are empty, return 2
            }
        }
 
        return -1; // should never reach this point
    }
 
    static void Main()
    {
        List<string> arr1 = new List<string> { "geeks", "geek" };
        List<string> brr1 = new List<string> { "geeks", "geeksforgeeks" };
        Console.WriteLine(FindLastPlayer(arr1, brr1));
        // should print 1
 
        List<string> arr2 = new List<string> { "a", "b" };
        List<string> brr2 = new List<string> { "a", "b" };
        Console.WriteLine(FindLastPlayer(arr2, brr2));
        // should print 2
    }
}


Javascript




function find_last_player(arr, brr) {
  let removed = {};
  let turn = 1;
  while (arr.length > 0 || brr.length > 0) {
    if (turn === 1) {
      if (arr.length === 0) {
        return 2;
      }
      let toRemove = arr.shift();
      removed[toRemove] = true;
    } else {
      if (brr.length === 0) {
        return 1;
      }
      let toRemove = brr.shift();
      removed[toRemove] = true;
    }
 
    turn = 3 - turn;
    let arrHasUnremovedElement = arr.some((element) => !removed[element]);
    if (!arrHasUnremovedElement) {
      let brrHasUnremovedElement = brr.some((element) => !removed[element]);
      if (!brrHasUnremovedElement) {
        return turn;
      }
    }
  }
  return -1;
}
let arr1 = ["geeks", "geek"];
let brr1 = ["geeks", "geeksforgeeks"];
console.log(find_last_player(arr1, brr1));
let arr2 = ["a", "b"];
let brr2 = ["a", "b"];
console.log(find_last_player(arr2, brr2));


Output

1
2







Time Complexity: O(n+m), where n and m are the lengths of the two arrays.

Auxiliary Space: O(n+m), for the hash map.



Last Updated : 23 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads