Skip to content

2697. Lexicographically Smallest Palindrome 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  string makeSmallestPalindrome(string s) {
    for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
      const int minChar = min(s[i], s[j]);
      s[i] = minChar;
      s[j] = minChar;
    }
    return s;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public String makeSmallestPalindrome(String s) {
    char[] chars = s.toCharArray();
    for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
      final char minChar = (char) Math.min(chars[i], chars[j]);
      chars[i] = minChar;
      chars[j] = minChar;
    }
    return new String(chars);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def makeSmallestPalindrome(self, s: str) -> str:
    chars = list(s)
    i = 0
    j = len(s) - 1

    while i < j:
      minChar = min(chars[i], chars[j])
      chars[i] = minChar
      chars[j] = minChar
      i += 1
      j -= 1

    return ''.join(chars)