Magicsheet logo

Lexicographically Smallest Palindrome

Easy
37.9%
Updated 6/1/2025

Lexicographically Smallest Palindrome

What is this problem about?

The "Lexicographically Smallest Palindrome interview question" involves transforming a given string into a palindrome using the minimum number of character replacements. If there are multiple ways to create a palindrome with the same number of changes, you must choose the one that is lexicographically smallest. This "Lexicographically Smallest Palindrome coding problem" is a classic exercise in two-pointer logic and greedy optimization.

Why is this asked in interviews?

This problem is a common choice for junior and mid-level roles at companies like Amazon and TikTok. It tests a candidate's understanding of the "Two Pointers interview pattern" and "Greedy interview pattern". It evaluates whether you can identify that a palindrome is inherently symmetric and that to achieve lexicographical minimality, you should always replace the larger character with the smaller one at each symmetric position.

Algorithmic pattern used

The two-pointer approach is the most efficient. You place one pointer at the start of the string and another at the end. At each step, compare the characters. If they are different, replace the lexicographically larger character with the smaller one to maintain the "lexicographically smallest" requirement. Since you must make the string a palindrome, every pair of characters at i and n-1-i must be equal.

Example explanation

String: "egcfe"

  1. Pointers at 'e' and 'e': Already equal. Move inward.
  2. Pointers at 'g' and 'f': They are different. 'f' is smaller than 'g'.
  3. Replace: Change 'g' to 'f'. String becomes "efcfe".
  4. Pointers at 'c': Middle character, no change needed. Result: "efcfe".

Common mistakes candidates make

  • Changing both characters: Replacing both characters with 'a' thinking it will be smaller, even though that might exceed the "minimum changes" requirement (if one character change was enough).
  • Ignoring lexicographical order: Choosing the larger character to replace the smaller one, resulting in a valid palindrome that isn't the smallest possible.
  • String immutability: Not converting the string to a character array in languages like Java or Python, which leads to O(n^2) time complexity due to repeated string slicing.

Interview preparation tip

Always remember the symmetry of palindromes. Any operation on one half of the string must be mirrored on the other. For lexicographical problems, greedy choices (like picking the smaller of two characters) are usually the winning strategy.

Similar Questions