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
  • Practice Game Theory
  • Game Theory in DSA
  • Nash Equilibrium
  • Normal form games
  • Minimax Algorithm
  • Impartial games
  • Combinatorial Game Theory
  • Nim Game
  • Grundy Numbers
  • Sprague Grundy Theorem
  • Minimax Algo
  • Alpha Beta Pruning
  • Zorbist Hashing
  • Coin Game
  • DP in Game Theory
  • Problems on Game Theory for CP
Open In App
Next Article:
Given two strings check which string makes a palindrome first
Next article icon

Make a palindromic string from given string

Last Updated : 29 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S consisting of lower-case English alphabets only, we have two players playing the game. The rules are as follows:  

  • The player can remove any character from the given string S and write it on paper on any side(left or right) of an empty string.
  • The player wins the game, if at any move he can get a palindromic string first of length > 1.
  • If a palindromic string cannot be formed, Player-2 is declared the winner.

Both play optimally with player-1 starting the game. The task is to find the winner of the game. 

Examples: 

Input: S = “abc” 
Output: Player-2 
Explanation: 
There are all unique characters due to which there 
is no way to form a palindromic string of length > 1

Input: S = “abccab” 
Output: Player-2 
Explanation: 
Initially, newString = “” is empty. 
Let Player-1 choose character ‘a’ and write it on paper. 
Then, S = “bccab” and newString = “a”. 
Now Player-2 chooses character ‘a’ from S and writes it on the left side of newString. 
Thus, S = “bccb” and newString = “aa”. 
Now, newString = “aa” is a palindrome of length 2. 
Hence, Player-2 wins. 

Approach: The idea is to formulate a condition in which Player-1 is always going to be the winner. If the condition fails, then Player-2 will win the game. 

  • If there is only one unique character occurring once in the given string, and the rest of the characters occurring more than 1, then Player-1 is going to be the winner, else Player-2 will always win.
  • If we have all characters that are occurring more than once in the given string, then Player-2 can always copy the Player-1 move in his first turn and wins.
  • Also, if we have more than one character in the string occurring one time only, then a palindrome string can never be formed(in the optimal case). Hence, again, Player-2 wins.

Below is the implementation of the above approach: 

C++




// C++ Implementation to find
// which player can form a palindromic
// string first in a game
 
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to find
// winner of the game
int palindromeWinner(string& S)
{
    // Array to Maintain frequency
    // of the characters in S
    int freq[26];
 
    // Initialise freq array with 0
    memset(freq, 0, sizeof freq);
 
    // Maintain count of all
    // distinct characters
    int count = 0;
 
    // Finding frequency of each character
    for (int i = 0; i < (int)S.length();
                                   ++i) {
        if (freq[S[i] - 'a'] == 0)
            count++;
 
        freq[S[i] - 'a']++;
    }
 
    // Count unique duplicate
    // characters
    int unique = 0;
    int duplicate = 0;
     
    // Loop to count the unique
    // duplicate characters
    for (int i = 0; i < 26; ++i) {
        if (freq[i] == 1)
            unique++;
        else if (freq[i] >= 2)
            duplicate++;
    }
 
    // Condition for Player-1
    // to be winner
    if (unique == 1 &&
     (unique + duplicate) == count)
        return 1;
 
    // Else Player-2 is
    // always winner
    return 2;
}
 
// Driven Code
int main()
{
    string S = "abcbc";
 
    // Function call
    cout << "Player-"
         << palindromeWinner(S)
         << endl;
 
    return 0;
}
 
 

Java




// Java implementation to find which
// player can form a palindromic
// string first in a game
import java.util.*;
 
class GFG{
     
// Function to find
// winner of the game
static int palindromeWinner(String S)
{
     
    // Array to maintain frequency
    // of the characters in S
    int freq[] = new int[26];
 
    // Initialise freq array with 0
    Arrays.fill(freq, 0);
 
    // Maintain count of all
    // distinct characters
    int count = 0;
 
    // Finding frequency of each character
    for(int i = 0; i < (int)S.length(); ++i)
    {
        if (freq[S.charAt(i) - 'a'] == 0)
            count++;
 
        freq[S.charAt(i) - 'a']++;
    }
 
    // Count unique duplicate
    // characters
    int unique = 0;
    int duplicate = 0;
     
    // Loop to count the unique
    // duplicate characters
    for(int i = 0; i < 26; ++i)
    {
        if (freq[i] == 1)
            unique++;
             
        else if (freq[i] >= 2)
            duplicate++;
    }
 
    // Condition for Player-1
    // to be winner
    if (unique == 1 &&
       (unique + duplicate) == count)
        return 1;
 
    // Else Player-2 is
    // always winner
    return 2;
}
     
// Driver Code
public static void main(String s[])
{
    String S = "abcbc";
         
    // Function call
    System.out.println("Player-" + palindromeWinner(S));
}
}
 
// This code is contributed by rutvik_56
 
 

Python3




# Python3 implementation to find
# which player can form a palindromic
# string first in a game
 
# Function to find
# winner of the game
def palindromeWinner(S):
     
    # Array to Maintain frequency
    # of the characters in S
    # initialise freq array with 0
    freq = [0 for i in range(0, 26)]
 
    # Maintain count of all
    # distinct characters
    count = 0
 
    # Finding frequency of each character
    for i in range(0, len(S)):
        if (freq[ord(S[i]) - 97] == 0):
            count += 1
 
        freq[ord(S[i]) - 97] += 1
 
    # Count unique duplicate
    # characters
    unique = 0
    duplicate = 0
     
    # Loop to count the unique
    # duplicate characters
    for i in range(0, 26):
        if (freq[i] == 1):
            unique += 1
             
        elif (freq[i] >= 2):
            duplicate += 1
 
    # Condition for Player-1
    # to be winner
    if (unique == 1 and
       (unique + duplicate) == count):
        return 1
 
    # Else Player-2 is
    # always winner
    return 2
 
# Driven Code
S = "abcbc";
 
# Function call
print("Player-", palindromeWinner(S))
 
# This code is contributed by Sanjit_Prasad
 
 

C#




// C# implementation to find which
// player can form a palindromic
// string first in a game
using System;
class GFG{
 
// Function to find
// winner of the game
static int palindromeWinner(string S)
{
  // Array to maintain frequency
  // of the characters in S
  int[] freq = new int[26];
 
  // Maintain count of all
  // distinct characters
  int count = 0;
 
  // Finding frequency of
  // each character
  for (int i = 0;
           i < (int)S.Length; ++i)
  {
    if (freq[S[i] - 'a'] == 0)
      count++;
 
    freq[S[i] - 'a']++;
  }
 
  // Count unique duplicate
  // characters
  int unique = 0;
  int duplicate = 0;
 
  // Loop to count the unique
  // duplicate characters
  for (int i = 0; i < 26; ++i)
  {
    if (freq[i] == 1)
      unique++;
 
    else if (freq[i] >= 2)
      duplicate++;
  }
 
  // Condition for Player-1
  // to be winner
  if (unique == 1 &&
     (unique + duplicate) ==
      count)
    return 1;
 
  // Else Player-2 is
  // always winner
  return 2;
}
 
// Driver Code
public static void Main(string[] s)
{
  string S = "abcbc";
 
  // Function call
  Console.Write("Player-" +
                 palindromeWinner(S));
}
}
 
// This code is contributed by Chitranayal
 
 

Javascript




<script>
// Javascript implementation to find which
// player can form a palindromic
// string first in a game
 
// Function to find
// winner of the game
function palindromeWinner(S)
{
    // Array to maintain frequency
    // of the characters in S
    let freq = new Array(26);
  
    // Initialise freq array with 0
    for(let i=0;i<26;i++)
    {
        freq[i]=0;
    }
  
    // Maintain count of all
    // distinct characters
    let count = 0;
  
    // Finding frequency of each character
    for(let i = 0; i < S.length; ++i)
    {
        if (freq[S[i].charCodeAt(0) - 'a'.charCodeAt(0)] == 0)
            count++;
  
        freq[S[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
    }
  
    // Count unique duplicate
    // characters
    let unique = 0;
    let duplicate = 0;
      
    // Loop to count the unique
    // duplicate characters
    for(let i = 0; i < 26; ++i)
    {
        if (freq[i] == 1)
            unique++;
              
        else if (freq[i] >= 2)
            duplicate++;
    }
  
    // Condition for Player-1
    // to be winner
    if (unique == 1 &&
       (unique + duplicate) == count)
        return 1;
  
    // Else Player-2 is
    // always winner
    return 2;
}
 
// Driver Code
let S = "abcbc";
// Function call
document.write("Player-" + palindromeWinner(S));
 
 
// This code is contributed by avanitrachhadiya2155
</script>
 
 
Output: 
Player-1

 

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.



Next Article
Given two strings check which string makes a palindrome first

S

Sanjit_Prasad
Improve
Article Tags :
  • DSA
  • Game Theory
  • Greedy
  • Strings
  • palindrome
Practice Tags :
  • Game Theory
  • Greedy
  • palindrome
  • Strings

Similar Reads

  • Form minimum number of Palindromic Strings from a given string
    Given a string S, the task is to divide the characters of S to form minimum number of palindromic strings. Note: There can be multiple correct answers. Examples: Input: S = "geeksforgeeks"Output: {eegksrskgee, o, f} Explanation: There should be at least 3 strings "eegksrskgee", "o", "f". All 3 forme
    12 min read
  • Check if K palindromic strings can be formed from a given string
    Given a string S of size N and an integer K, the task is to find whether the characters of the string can be arranged to make K palindromic strings simultaneously. Examples: Input: S = "annabelle", K = 2 Output: Yes Explanation: All characters of string S can be distributed into "elble" and "anna" w
    7 min read
  • Given two strings check which string makes a palindrome first
    Given two strings 'A' and 'B' of equal length. Two players play a game where they both pick a character from their respective strings (First picks from A and second from B) and put into a third string (which is initially empty). The player that can make the third string palindrome, is winner. If fir
    6 min read
  • Count Palindromic Substrings in a Binary String
    Given a binary string S i.e. which consists only of 0's and 1's. Calculate the number of substrings of S which are palindromes. String S contains at most two 1's. Examples: Input: S = "011"Output: 4Explanation: "0", "1", "1" and "11" are the palindromic substrings. Input: S = "0" Output: 1Explanatio
    7 min read
  • All distinct palindromic sub-strings of a given string
    Given a string str of lowercase ASCII characters. The task is to find all the distinct continuous palindromic sub-strings which are present in the string str. Examples: Input: str = "abaaa"Output: [ "a", "aa", "aaa", "aba", "b" ]Explanation: All 5 distinct continuous palindromic sub-strings are list
    15+ min read
  • Find all Palindrome Strings in given Array of strings
    Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array. Examples: Input: arr[] = {"abc", "car", "ada", "racecar", "cool"}Output: "ada", "ra
    6 min read
  • Count of Palindrome Strings in given Array of strings
    Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to return the count of all palindromic string in the array. Examples: Input: arr[] = {"abc","car","ada","racecar","cool"}Output: 2Explanation: "ada" and "racecar" are the two palindrome
    5 min read
  • Lexicographically all Shortest Palindromic Substrings from a given string
    Given a string s of size N. The task is to find lexicographically all the shortest palindromic substrings from the given string. Examples: Input: s= "programming" Output: a g i m n o p r Explanation: The Lexicographical shortest palindrome substring for the word "programming" will be the single char
    4 min read
  • Make String Anti-Palindrome
    Given a string S of length N is said to be an Anti-palindrome string if, for each 0 ? i ? N-1, Si != S(N - 1 ? i). The task is to print Anti-Palindrome String formed, If it is not possible to find print "-1" Examples: Input: S = "abdcccdb"Output: "cbbaccdd"Explanation: cbbaccdd is an Anti-palindrome
    6 min read
  • Minimum size substring to be removed to make a given string palindromic
    Given a string S, the task is to print the string after removing the minimum size substring such that S is a palindrome or not. Examples: Input: S = "pqrstsuvwrqp"Output: pqrstsrqpExplanation:Removal of the substring "uvw" modifies S to a palindromic string. Input: S = "geeksforskeeg"Output: geeksfs
    15+ 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