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:
Minimum replacements in a string to make adjacent characters unequal
Next article icon

Minimize replacement of characters to its nearest alphabet to make a string palindromic

Last Updated : 03 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 incremented then it becomes a and if a is decremented then it becomes z.

Examples:

Input: S = “arcehesmz”
Output: 16
Explanation:
The possible transformation that given the minimum count of operation is: 

  • Decrease 1st character ‘a’ by 1 to get ‘z’. Count of operation = 1
  • Decrease 3rd character ‘c’ by 10 to get ‘s’. Count of operations = 1 + 10 = 11
  • Increase 8th character ‘m’ by 5  to get ‘r’. Count of operations = 11 + 5 = 16.

Therefore, the total count of operations is 16.

Input: S = “abccdb”
Output: 3
Explanation:
The possible transformation that given the minimum count of operation is: 

  • Increase 1st character ‘a’ by 1 to get ‘b’. Count of operation = 1
  • Increase 2nd character ‘b’ by 2 to get ‘d’. Count of operations = 1 + 2 = 3.

Naive Approach: The simplest approach is to generate all possible strings of length N. Then check for each string, if its a palindrome. If any string is found to be palindromic then find the cost of operation required to convert the given string into that string. Repeat the above steps for all the generated strings and print the minimum cost calculated among all the costs. 

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

Efficient Approach: To optimize the above approach, the idea is to traverse the given string and find the change for each position independently. Follow the below steps to solve the problem:

  1. Traverse through the given string over the range [0, (N/2) – 1].
  2. For each character at index i, find the absolute difference between the characters at indices i and (N – i – 1).
  3. There can be two possible differences i.e., the difference when the character at i is incremented to character at index (N – i – 1) and when it is decremented at that index.
  4. Take the minimum of both and add it to the result.
  5. After the above steps, print the minimum cost calculated.

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 minimum number
// of operations required to convert
// the given string into palindrome
int minOperations(string s)
{
    int len = s.length();
    int result = 0;
 
    // Iterate till half of the string
    for (int i = 0; i < len / 2; i++) {
 
        // Find the absolute difference
        // between the characters
        int D1 = max(s[i], s[len - 1 - i])
                - min(s[i], s[len - 1 - i]);
 
        int D2 = 26 - D1;
 
        // Adding the minimum difference
        // of the two result
        result += min(D1, D2);
    }
 
    // Return the result
    return result;
}
 
// Driver Code
int main()
{
    // Given string
    string s = "abccdb";
 
    // Function Call
    cout << minOperations(s);
 
    return 0;
}
 
 

Java




// Java program for the above approach
public class GFG{
     
// Function to find the minimum number
// of operations required to convert
// the given string into palindrome
public static int minOperations(String s)
{
    int len = s.length();
    int result = 0;
 
    // Iterate till half of the string
    for(int i = 0; i < len / 2; i++)
    {
         
        // Find the absolute difference
        // between the characters
        int D1 = Math.max(s.charAt(i),
                          s.charAt(len - 1 - i)) -
                 Math.min(s.charAt(i),
                          s.charAt(len - 1 - i));
 
        int D2 = 26 - D1;
 
        // Adding the minimum difference
        // of the two result
        result += Math.min(D1, D2);
    }
 
    // Return the result
    return result;
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given string
    String s = "abccdb";
 
    // Function call
    System.out.println(minOperations(s));
}
}
 
// This code is contributed by divyeshrabadiya07
 
 

Python3




# Python3 program for the above approach
 
# Function to find the minimum number
# of operations required to convert
# the given string into palindrome
def minOperations(s):
 
    length = len(s)
    result = 0
 
    # Iterate till half of the string
    for i in range(length // 2):
 
        # Find the absolute difference
        # between the characters
        D1 = (ord(max(s[i], s[length - 1 - i])) -
              ord(min(s[i], s[length - 1 - i])))
         
        D2 = 26 - D1
 
        # Adding the minimum difference
        # of the two result
        result += min(D1, D2)
 
    # Return the result
    return result
 
# Driver Code
 
# Given string
s = "abccdb"
 
# Function call
print(minOperations(s))
 
# This code is contributed by Shivam Singh
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
     
// Function to find the minimum number
// of operations required to convert
// the given string into palindrome
public static int minOperations(String s)
{
    int len = s.Length;
    int result = 0;
 
    // Iterate till half of the string
    for(int i = 0; i < len / 2; i++)
    {
         
        // Find the absolute difference
        // between the characters
        int D1 = Math.Max(s[i],
                          s[len - 1 - i]) -
                 Math.Min(s[i],
                          s[len - 1 - i]);
 
        int D2 = 26 - D1;
 
        // Adding the minimum difference
        // of the two result
        result += Math.Min(D1, D2);
    }
 
    // Return the result
    return result;
}
 
// Driver code
public static void Main(String[] args)
{
     
    // Given string
    String s = "abccdb";
 
    // Function call
    Console.WriteLine(minOperations(s));
}
}
 
// This code is contributed by Amit Katiyar
 
 

Javascript




<script>
      // JavaScript program for the above approach
 
      // Function to find the minimum number
      // of operations required to convert
      // the given string into palindrome
      function minOperations(s)
      {
        var len = s.length;
        var result = 0;
 
        // Iterate till half of the string
        for (var i = 0; i < len / 2; i++)
        {
         
          // Find the absolute difference
          // between the characters
          var D1 =
            Math.max(s[i].charCodeAt(0), s[len - 1 - i].charCodeAt(0)) -
            Math.min(s[i].charCodeAt(0), s[len - 1 - i].charCodeAt(0));
 
          var D2 = 26 - D1;
 
          // Adding the minimum difference
          // of the two result
          result += Math.min(D1, D2);
        }
 
        // Return the result
        return result;
      }
 
      // Driver Code
       
      // Given string
      var s = "abccdb";
       
      // Function Call
      document.write(minOperations(s));
       
      // This code is contributed by rdtank.
    </script>
 
 
Output
3

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



Next Article
Minimum replacements in a string to make adjacent characters unequal

C

cherau
Improve
Article Tags :
  • Combinatorial
  • DSA
  • Greedy
  • Python
  • Searching
  • Strings
  • palindrome
  • permutation
  • strings
Practice Tags :
  • Combinatorial
  • Greedy
  • palindrome
  • permutation
  • python
  • Searching
  • Strings
  • Strings

Similar Reads

  • Minimum number of characters to be replaced to make a given string Palindrome
    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 t
    5 min read
  • Minimize replacements by previous or next alphabet required to make all characters of a string the same
    Given a string S of length N consisting of lowercase alphabets, the task is to find the minimum number of operations required to make all the characters of the string S the same. In each operation, choose any character and replace it with its next or previous alphabet. Note: The alphabets are consid
    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 replacements in a string to make adjacent characters unequal
    Given a lowercase character string str of size N. In one operation any character can be changed into some other character. The task is to find the minimum number of operations such that no two adjacent characters are equal.Examples: Input: Str = "caaab" Output: 1 Explanation: Change the second a to
    6 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
  • Minimum moves to make String Palindrome incrementing all characters of Substrings
    Given a string S of length N, the task is to find the minimum number of moves required to make a string palindrome where in each move you can select any substring and increment all the characters of the substring by 1. Examples: Input: S = "264341"Output: 2?Explanation: We can perform the following
    6 min read
  • Minimize characters to be changed to make the left and right rotation of a string same
    Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc
    8 min read
  • Remove a character from a string to make it a palindrome
    Given a string, we need to check whether it is possible to make this string a palindrome after removing exactly one character from this. Examples: Input : str = “abcba” Output : Yes we can remove character ‘c’ to make string palindrome Input : str = “abcbea” Output : Yes we can remove character ‘e’
    10 min read
  • Minimum number of deletions to make a string palindrome | Set 2
    Given a string A, compute the minimum number of characters you need to delete to make resulting string a palindrome. Examples: Input : baca Output : 1 Input : geek Output : 2 We have discussed one approach in below post. Minimum number of deletions to make a string palindrome Below approach will use
    9 min read
  • Minimum Count of Bit flips required to make a Binary String Palindromic
    Given an integer N, the task is to find the minimum number of bits required to be flipped to convert the binary representation of N into a palindrome. Examples: Input: N = 12 Output: 2 Explanation: Binary String representing 12 = "1100". To make "1100" a palindrome, convert the string to "0110". The
    7 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