Leetcode 2697. Lexicographically Smallest Palindrome
You are given a string s
consisting of lowercase English letters, that can be rearranged to form a palindrome. Write a function that rearranges the input string s
to form the lexicographically smallest palindrome.
s
?
n <= 10^5
.s
can be rearranged to form a palindrome.To solve this problem, the approach is to construct a palindrome by considering the following facts:
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class LexicographicallySmallestPalindrome {
public String createSmallestPalindrome(String s) {
if (s == null || s.length() == 0) {
return s;
}
Map<Character, Integer> charCount = new HashMap<>();
for (char c : s.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
Character oddChar = null;
int oddCount = 0;
PriorityQueue<Character> minHeap = new PriorityQueue<>();
for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
char character = entry.getKey();
int count = entry.getValue();
if (count % 2 == 1) {
oddCount++;
oddChar = character;
}
minHeap.add(character);
}
if (oddCount > 1) {
return ""; // This case shouldn't occur given the problem constraint
}
StringBuilder firstHalf = new StringBuilder();
while (!minHeap.isEmpty()) {
char character = minHeap.poll();
int count = charCount.get(character);
for (int i = 0; i < count / 2; i++) {
firstHalf.append(character);
}
}
String firstHalfStr = firstHalf.toString();
StringBuilder secondHalf = new StringBuilder(firstHalfStr).reverse();
if (oddChar != null) {
return firstHalfStr + oddChar + secondHalf.toString();
}
return firstHalfStr + secondHalf.toString();
}
public static void main(String[] args) {
LexicographicallySmallestPalindrome solution = new LexicographicallySmallestPalindrome();
System.out.println(solution.createSmallestPalindrome("aabb")); // Should return "abba"
System.out.println(solution.createSmallestPalindrome("aabbcc")); // Should return "abccba"
System.out.println(solution.createSmallestPalindrome("racecar")); // Should return "aaccerrcaac"
}
}
n
is the length of the string s
.k
is the number of distinct characters in s
.Thus, the overall time complexity is O(n + k log k), where n
is the length of the string and k
is the number of distinct characters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?