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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check if string remains palindrome after removing given number of characters
Next article icon

Minimum number of characters to be replaced to make a given string Palindrome

Last Updated : 31 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given string str, the task is to find the minimum number of characters to be replaced to make a given string palindrome. Replacing a character means replacing it with any single character in the same position. We are not allowed to remove or add any characters. 

If there are multiple answers, print the lexicographically smallest string.

Examples:  

Input: str = "geeks" Output: 2 geeks can be converted to geeeg to make it palindrome by replacing minimum characters.  Input: str = "ameba" Output: 1 We can get "abeba" or "amema" with only 1 change.  Among those two, "abeba" is lexicographically smallest. 

Approach: Run a loop from 0 up to (length)/2-1 and check if a character at the i-th index i.e. s[i]!=s[length-i-1], then we will replace the alphabetically larger character with the one which is alphabetically smaller among them and continue the same process until all the elements get traversed.

Below is the implementation of the above approach:  

C++




// C++ Implementation of the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to find the minimum number
// character change required
  
void change(string s)
{
 
    // Finding the length of the string
    int n = s.length();
 
    // To store the number of replacement operations
    int cc = 0;
 
    for(int i=0;i<n/2;i++)
    {
 
        // If the characters at location
        // i and n-i-1 are same then
        // no change is required
        if(s[i]== s[n-i-1])
            continue;
 
        // Counting one change operation
        cc+= 1;
 
        // Changing the character with higher
        // ascii value with lower ascii value
        if(s[i]<s[n-i-1])
            s[n-i-1]= s[i] ;
        else
            s[i]= s[n-i-1] ;
    }
    printf("Minimum characters to be replaced = %d\n", (cc)) ;
    cout<<s<<endl;
}
// Driver code
int main()
{
string s = "geeks";
change((s));
return 0;
}
//contributed by Arnab Kundu
 
 

Java




// Java Implementation of the above approach
import java.util.*;
 
class GFG
{
 
// Function to find the minimum number
// character change required
static void change(String s)
{
 
    // Finding the length of the string
    int n = s.length();
 
    // To store the number of replacement operations
    int cc = 0;
 
    for(int i = 0; i < n/2; i++)
    {
 
        // If the characters at location
        // i and n-i-1 are same then
        // no change is required
        if(s.charAt(i) == s.charAt(n - i - 1))
            continue;
 
        // Counting one change operation
        cc += 1;
 
        // Changing the character with higher
        // ascii value with lower ascii value
        if(s.charAt(i) < s.charAt(n - i - 1))
            s = s.replace(s.charAt(n - i - 1),s.charAt(i));
        else
            s = s.replace(s.charAt(n-1),s.charAt(n - i - 1));
    }
    System.out.println("Minimum characters to be replaced = "+(cc)) ;
    System.out.println(s);
}
 
// Driver code
public static void main(String args[])
{
    String s = "geeks";
    change((s));
 
}
}
 
// This code is contributed by
// Nikhil Gupta
 
 

Python




# Python Implementation of the above approach
 
# Function to find the minimum number
# character change required
import math as ma
def change(s):
 
    # Finding the length of the string
    n = len(s)
 
    # To store the number of replacement operations
    cc = 0
 
    for i in range(n//2):
 
        # If the characters at location
        # i and n-i-1 are same then
        # no change is required
        if(s[i]== s[n-i-1]):
            continue
 
        # Counting one change operation
        cc+= 1
 
        # Changing the character with higher
        # ascii value with lower ascii value
        if(s[i]<s[n-i-1]):
            s[n-i-1]= s[i]
        else:
            s[i]= s[n-i-1]
 
    print("Minimum characters to be replaced = ", str(cc))
    print(*s, sep ="")
     
# Driver code
s = "geeks"
change(list(s))
 
 

C#




// C# Implementation of the above approach
using System;
     
class GFG
{
 
// Function to find the minimum number
// character change required
static void change(String s)
{
 
    // Finding the length of the string
    int n = s.Length;
 
    // To store the number of
    //replacement operations
    int cc = 0;
 
    for(int i = 0; i < n / 2; i++)
    {
 
        // If the characters at location
        // i and n-i-1 are same then
        // no change is required
        if(s[i] == s[n - i - 1])
            continue;
 
        // Counting one change operation
        cc += 1;
 
        // Changing the character with higher
        // ascii value with lower ascii value
        if(s[i] < s[n - i - 1])
            s = s.Replace(s[n - i - 1], s[i]);
        else
            s = s.Replace(s[n], s[n - i - 1]);
    }
    Console.WriteLine("Minimum characters " +
                      "to be replaced = " + (cc));
    Console.WriteLine(s);
}
 
// Driver code
public static void Main(String []args)
{
    String s = "geeks";
    change((s));
}
}
 
// This code contributed by Rajput-Ji
 
 

PHP




<?php
// PHP Implementation of the above approach
 
// Function to find the minimum number
// character change required
   
function change($s)
{
  
    // Finding the length of the string
    $n = strlen($s);
  
    // To store the number of replacement operations
    $cc = 0;
  
    for($i=0;$i<$n/2;$i++)
    {
  
        // If the characters at location
        // i and n-i-1 are same then
        // no change is required
        if($s[$i]== $s[$n-$i-1])
            continue;
  
        // Counting one change operation
        $cc+= 1;
  
        // Changing the character with higher
        // ascii value with lower ascii value
        if($s[$i]<$s[$n-$i-1])
            $s[$n-$i-1]= $s[$i] ;
        else
            $s[$i]= $s[$n-$i-1] ;
    }
    echo "Minimum characters to be replaced = ". $cc."\n" ;
    echo $s."\n";
}
// Driver code
 
$s = "geeks";
change(($s));
return 0;
?>
 
 

Javascript




<script>
 
// Javascript Implementation of the above approach
 
// Function to find the minimum number
// character change required
  
function change(s)
{
 
    // Finding the length of the string
    var n = s.length;
 
    // To store the number of replacement operations
    var cc = 0;
 
    for(var i=0;i<n/2;i++)
    {
 
        // If the characters at location
        // i and n-i-1 are same then
        // no change is required
        if(s[i]== s[n-i-1])
            continue;
 
        // Counting one change operation
        cc+= 1;
 
        // Changing the character with higher
        // ascii value with lower ascii value
        if(s[i]<s[n-i-1])
            s[n-i-1]= s[i] ;
        else
            s[i]= s[n-i-1] ;
    }
    document.write("Minimum characters to be replaced = " + (cc)+"<br>");
    document.write(s.join('') + "<br>");
}
 
// Driver code
var s = "geeks".split('');
change((s));
 
</script>
 
 
Output: 
Minimum characters to be replaced =  2 geeeg

 



Next Article
Check if string remains palindrome after removing given number of characters

I

indrajit1
Improve
Article Tags :
  • Python
  • palindrome
Practice Tags :
  • palindrome
  • python

Similar Reads

  • Minimize replacement of characters to its nearest alphabet to make a string palindromic
    Given a string S of length N consisting of lowercase alphabets, the task is to find the minimum number of operations to convert the given string into a palindrome. In one operation, choose any character and replace it by its next or previous alphabet. Note: The alphabets are cyclic i.e., if z is inc
    6 min read
  • Minimum characters to be replaced to make a string concatenation of a K-length palindromic string
    Given a string S of size N and a positive integer K ( where N % K = 0), the task is to find the minimum number of characters required to be replaced such that the string is K-periodic and the K-length periodic string must be a palindrome. Examples: Input: S = "abaaba", K = 3Output: 0Explanation: The
    11 min read
  • Minimum number of palindromic subsequences to be removed to empty a binary string
    Given a binary string, count minimum number of subsequences to be removed to make it an empty string. Examples : Input: str[] = "10001" Output: 1 Since the whole string is palindrome, we need only one removal. Input: str[] = "10001001" Output: 2 We can remove the middle 1 as first removal, after fir
    6 min read
  • Check if string remains palindrome after removing given number of characters
    Given a palindromic string str and an integer N. The task is to find if it is possible to remove exactly N characters from the given string such that the string remains a palindrome. Examples: Input: str = "abba", N = 1 Output: Yes Remove 'b' and the remaining string "aba" is still a palindrome. Inp
    3 min read
  • Replace minimal number of characters to make all characters pair wise distinct
    Given a string consisting of only lowercase English alphabets. The task is to find and replace the minimal number of characters with any lower case character in the given string such that all pairs of characters formed from the string are distinct. If it is impossible to do so, print "IMPOSSIBLE". N
    10 min read
  • Minimum reduce operations to convert a given string into a palindrome
    Given a String find the minimum number of reduce operations required to convert a given string into a palindrome. In a reduce operation, we can change character to a immediate lower value. For example b can be converted to a. Examples : Input : abcd Output : 4 We need to reduce c once and d three ti
    4 min read
  • Minimum removal of characters required such that permutation of given string is a palindrome
    Given string str consisting of lowercase letters, the task is to find the minimum number of characters to be deleted from the given string such that any permutation of the remaining string is a palindrome. Examples: Input: str="aba"Output: 1Explanation: Removing 'b' generates a palindromic string "a
    7 min read
  • 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
  • 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
  • Minimize replacements or swapping of same indexed characters required to make two given strings palindromic
    Given two strings, str1 and str2 consisting of N lowercase alphabets, the task is to find the minimum count of operations of the following two types to make both the strings palindromic string. Replace any character of the strings to any other character([a - z]).Swap any two characters present at th
    8 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