Lexicographically Smallest Palindrome — LeetCode 2697 Python Solution

EasyGreedyTwo PointersString
Problem
#2697
Reading time
2 min

The 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.

Example

Input
s = "egcfe"
Output
"efcfe"
Explanation
The minimum number of operations to make "egcfe" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "efcfe", by changing 'g'.

Python solution

Python
class Solution:
    def makeSmallestPalindrome(self, s: str) -> str:
        cs = list(s)
        i, j = 0, len(s) - 1
        while i < j:
            cs[i] = cs[j] = min(cs[i], cs[j])
            i, j = i + 1, j - 1
        return "".join(cs)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2697. Lexicographically Smallest Palindrome is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2697. Lexicographically Smallest Palindrome?
LeetCode 2697. Lexicographically Smallest Palindrome is rated Easy on LeetCode.
What is the time complexity of LeetCode 2697. Lexicographically Smallest Palindrome?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2697. Lexicographically Smallest Palindrome?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2697. Lexicographically Smallest Palindrome cover?
LeetCode 2697. Lexicographically Smallest Palindrome is tagged Greedy, Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview