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


In this article, we will discuss a fascinating algorithmic problem: "Minimize replacement of characters to its nearest alphabet to make a string palindromic." This problem is intriguing because it involves string manipulation, palindrome checking, and the concept of ASCII values for characters. Let's dive into the problem.

Problem Statement

Given a string of characters, the task is to transform it into a palindrome with the minimum number of replacements. These replacements are made by changing a character to its nearest alphabet.

Understanding the Problem

A palindrome is a word, phrase, number, or other sequences of characters that reads the same backward as forward. Our goal is to minimize the total number of replacements needed to transform a given string into a palindrome.

For example, consider the string "abc". To transform it into a palindrome, we can replace 'c' with 'a' which requires two replacements ('c' to 'b' and 'b' to 'a'). Hence, the minimum number of replacements is 2.

Algorithmic Approach

To solve this problem, we'll use a two-pointer approach. Here are the steps −

  • Initialize two pointers, one at the start and the other at the end of the string.

  • Compare the characters at the pointers.

  • If they are equal, move the pointers inward.

  • If they are not equal, replace the farther character from 'a' with the closer one and increment the count of replacements. Also, move the pointers inward.

  • Repeat steps 2-4 until the start pointer is not less than the end pointer.

Example

Following are the programs that implements the above approach −

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int makePalindrome(char* str) {
   int len = strlen(str);
   int res = 0;
   
   // Loop through the string from both ends and calculate the absolute difference between characters
   // Add the absolute difference to the result
   for (int i = 0, j = len - 1; i < j; i++, j--) {
      res += abs(str[i] - str[j]);
   }
   return res;
}

// Main function to test the makePalindrome function
int main() {
   char str[] = "abcde";
   printf("Minimum replacements: %d\n", makePalindrome(str));
   return 0;
}

Output

Minimum replacements: 6
#include<bits/stdc++.h>
using namespace std;

int makePalindrome(string str) {
   int len = str.size();
   int res = 0;
   for (int i = 0, j = len - 1; i < j; i++, j--) {
      res += abs(str[i] - str[j]);
   }
   return res;
}

int main() {
   string str="abcde";
   cout << "Minimum replacements: " << makePalindrome(str);
   return 0;
}

Output

Minimum replacements: 6
import java.util.Scanner;

public class Main {
   public static int makePalindrome(String str) {
      int len = str.length();
      int res = 0;
       
      // Loop through the string from both ends and calculate the absolute difference between characters
      // Add the absolute difference to the result
      for (int i = 0, j = len - 1; i < j; i++, j--) {
         res += Math.abs(str.charAt(i) - str.charAt(j));
      }
      return res;
   }

   // Main function to test the makePalindrome function
   public static void main(String[] args) {
      String str = "abcde";
      System.out.println("Minimum replacements: " + makePalindrome(str));
   }
}

Output

Minimum replacements: 6
def make_palindrome(s):
   n = len(s)
   res = 0
   
   # Loop through the string from both ends and calculate the absolute difference between characters
   # Add the absolute difference to the result
   for i in range(n // 2):
      res += abs(ord(s[i]) - ord(s[n - i - 1]))
   return res

# Main function to test the make_palindrome function
def main():
   s = "abcde"
   print("Minimum replacements:", make_palindrome(s))

if __name__ == "__main__":
   main()

Output

Minimum replacements: 6

Testcase Example

Let's run an example −

Consider the string "abcde". The above program will output "Minimum replacements: 4". Here's why −

  • Compare 'a' and 'e'. They are not the same, so replace 'e' with 'a'. This needs 4 replacements. Our string is now "abcda".

  • Compare 'b' and 'd'. They are not the same, so replace 'd' with 'b'. This needs 2 replacements. Our string is now "abcba".

  • Now, the string is a palindrome. So, the total minimum replacements are 4 + 2 = 6.

Remember, the number of replacements is calculated as the absolute difference of ASCII values of the characters.

Conclusion

This problem is an excellent example of how simple string manipulation and two-pointer technique can solve relatively complex problems. Understanding such problems not only helps in coding interviews but also improves overall problem-solving skills.

Updated on: 23-Oct-2023

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements