Lexicographically Smallest Palindrome - Problem

You're given a string s consisting of lowercase English letters. Your mission is to transform it into a palindrome using the minimum number of character replacements possible.

Here's the twist: if multiple palindromes can be created with the same minimum operations, you must choose the lexicographically smallest one (the one that would appear first in a dictionary).

What makes a string lexicographically smaller?
String a is lexicographically smaller than string b if at the first position where they differ, a has a letter that comes earlier in the alphabet.

Goal: Return the lexicographically smallest palindrome that requires the minimum number of operations.

Example: "abcd" โ†’ "abba" (2 operations: change 'c' to 'b' and 'd' to 'a')

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "egcfe"
โ€บ Output: "efcfe"
๐Ÿ’ก Note: The minimum operations needed are 2: change 'g' to 'f' and 'd' to 'f'. Among all possible palindromes with 2 operations, "efcfe" is lexicographically smallest.
example_2.py โ€” Already Optimal
$ Input: s = "abcd"
โ€บ Output: "abba"
๐Ÿ’ก Note: We need 2 operations: change 'c' to 'b' and 'd' to 'a'. This creates "abba" which is the lexicographically smallest palindrome with minimum operations.
example_3.py โ€” Single Character
$ Input: s = "a"
โ€บ Output: "a"
๐Ÿ’ก Note: Single character strings are already palindromes, so no operations needed.

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists of lowercase English letters only
  • Follow-up: Can you solve this in O(n) time with O(1) extra space?

Visualization

Tap to expand
Palindrome Mirror MagicMirror LinedPosition 0cPosition 1cPosition 2aPosition 3d > a, choose 'a'c = c, no changeaAftercca
Understanding the Visualization
1
Set Up Mirrors
Place two pointers at opposite ends of the string like mirrors facing each other
2
Check Reflection
Compare characters at mirror positions - do they match?
3
Choose Wisely
If they don't match, pick the lexicographically smaller character
4
Apply to Both
Set both mirror positions to the chosen character
5
Move Inward
Move both pointers toward the center and repeat
Key Takeaway
๐ŸŽฏ Key Insight: The greedy choice of always selecting the lexicographically smaller character for mismatched pairs guarantees both minimum operations and the smallest possible palindrome.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
82.0K Views
Medium Frequency
~12 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen