Finding the Closest Palindrome to a Given String

Swati Meher
2 min readJun 3, 2024

--

Introduction:

Palindromes are fascinating constructs in the world of strings. They read the same forwards and backwards, and finding the closest palindrome to a given string is an interesting problem. This article delves into solving this problem using Python, structured into three categories: Problem Statement, Code Logic, Code Implementation, and Conclusion.

Problem Statement:

The task is to find the closest palindrome to a given string. A palindrome is a string that reads the same forwards and backwards. For example, the closest palindrome to “cat” is “cac”, and for “madan” it is “madam”. The goal is to transform the given string into a palindrome by making the minimum number of changes.

Code Logic:

To achieve the closest palindrome:

  1. Input Handling: Read the string input from the user.
  2. Two-pointer Approach: Utilize a two-pointer approach to compare and adjust characters from both ends of the string towards the center.
  3. Character Adjustment: If characters at the two pointers do not match, modify one of them to make the characters equal, ensuring minimal changes.
  4. Construct Result: After processing, reconstruct the string from the modified list of characters.

Python Code Implementation:

Here is the complete Python code that implements the above logic:

# Write your code here

n = input()

def closest_palindrome(s):
chars = list(s)
left, right = 0, len(s) - 1

while left < right:
if chars[left] != chars[right]:
# Make the right character match the left character
chars[right] = chars[left]
left += 1
right -= 1

return ''.join(chars)

# Calling the function and printing the result
print(closest_palindrome(n))

Output Demonstration:

#example 1

Input:
cat

Output:
cac

#example 2

Input:
madan

Output:
madam

Conclusion:

Finding the closest palindrome to a given string can be efficiently solved using a two-pointer approach. By systematically adjusting characters from both ends of the string towards the center, we ensure minimal changes and achieve the closest possible palindrome. This method is simple yet powerful, demonstrating how basic string manipulation techniques can solve interesting problems in computer science. The provided Python code is not only easy to understand but also practical for a wide range of applications where palindromes are relevant.

Happy Coding ;)

--

--

Swati Meher

Data Analyst | Gadget Lover | Hoping to reach 300 Followers here.