Lexicographically Smallest Palindrome - Problem

You are given a string s consisting of lowercase English letters, and you are allowed to perform operations on it. In one operation, you can replace a character in s with another lowercase English letter.

Your task is to make s a palindrome with the minimum number of operations possible. If there are multiple palindromes that can be made using the minimum number of operations, make the lexicographically smallest one.

A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.

Return the resulting palindrome string.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcd"
Output: "abba"
💡 Note: Compare 'a' and 'd': choose 'a' for both positions. Compare 'b' and 'c': choose 'b' for both positions. Result is "abba" with 2 operations.
Example 2 — Already Palindrome
$ Input: s = "aa"
Output: "aa"
💡 Note: String is already a palindrome, no operations needed.
Example 3 — Single Character
$ Input: s = "a"
Output: "a"
💡 Note: Single character is always a palindrome, no operations needed.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters only

Visualization

Tap to expand
Lexicographically Smallest Palindrome INPUT String s = "abcd" a i=0 b i=1 c i=2 d i=3 Two Pointers Approach left right Compare s[left] with s[right] Length n = 4 Pairs to check: 2 ALGORITHM STEPS 1 Initialize Pointers left=0, right=n-1 2 Compare Pair (0,3) 'a' vs 'd': pick min('a','d')='a' a --> a a 3 Compare Pair (1,2) 'b' vs 'c': pick min('b','c')='b' b --> b b 4 Build Result Combine: "a" + "bb" + "a" Operations: 2 (change d-->a, c-->b) Time: O(n), Space: O(n) FINAL RESULT Palindrome Achieved! a b b a mirror Output: "abba" Verification: Palindrome: OK Lex Smallest: OK Min Operations: OK SUCCESS Key Insight: For each mismatched pair at positions (i, n-1-i), always choose the lexicographically smaller character for both positions. This ensures minimum operations AND the smallest possible palindrome. TutorialsPoint - Lexicographically Smallest Palindrome | Optimal Solution (Two Pointers)
Asked in
Google 25 Amazon 20 Microsoft 15
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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