Lexicographically Smallest Palindrome — LeetCode 2697 Python Solution
- Problem
- #2697
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.