#2697

Lexicographically Smallest Palindrome

Easy
Two PointersStringGreedyTwo PointersGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a two-pointer technique to efficiently convert the string into a palindrome while ensuring it is lexicographically smallest. This method minimizes operations by directly comparing characters from both ends of the string.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, one at the start and one at the end of the string.
  2. 2Step 2: While the left pointer is less than or equal to the right pointer, compare the characters at both pointers.
  3. 3Step 3: If they are different, replace the larger character with the smaller one to ensure the palindrome is lexicographically smallest.
  4. 4Step 4: Move the pointers towards the center and repeat until all characters are checked.
solution.py14 lines
1def make_palindrome(s):
2    s = list(s)
3    left, right = 0, len(s) - 1
4    while left <= right:
5        if s[left] != s[right]:
6            min_char = min(s[left], s[right])
7            s[left] = min_char
8            s[right] = min_char
9        left += 1
10        right -= 1
11    return ''.join(s)
12
13# Example usage:
14print(make_palindrome('egcfe'))

Complexity note: The complexity is O(n) because we only traverse the string once with two pointers, making it efficient in terms of time. The space complexity is O(n) due to the conversion of the string into a character array.

  • 1Changing the larger character to the smaller one ensures the palindrome is lexicographically smallest.
  • 2Using two pointers allows for efficient comparison and modification of characters.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.