3734. Lexicographically Smallest Palindromic Permutation Greater Than Target
</> Solution
/**
* Problem: LeetCode 3734 - Lexicographically Smallest Palindromic Permutation Greater Than Target
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public String lexPalindromicPermutation(String s, String target) {
int n = s.length();
int[] freq = new int[26];
for (char c : s.toCharArray()) freq[c - 'a']++;
// Palindrome possible only if at most 1 odd frequency
int oddCount = 0;
for (int f : freq) if (f % 2 != 0) oddCount++;
if (oddCount > 1) return "";
// Middle character for odd length
char mid = 0;
for (int i = 0; i < 26; i++)
if (freq[i] % 2 != 0) { mid = (char) ('a' + i); break; }
int halfLen = n / 2;
// Build smallest left half
char[] smallestHalf = buildSmallestHalf(freq, halfLen);
String smallest = buildPalindrome(smallestHalf, mid, n);
if (smallest.compareTo(target) > 0) return smallest;
// target's left half (first halfLen chars)
char[] tHalf = target.substring(0, halfLen).toCharArray();
// Strategy: go position by position, try to match tHalf greedily
// At each pos, either:
// - place same char as tHalf[pos] and continue (greedy match)
// - place char > tHalf[pos] and fill rest with smallest -> candidate
// Also check: if we matched entire tHalf, check mid character case
int[] avail = new int[26];
for (int i = 0; i < 26; i++) avail[i] = freq[i] / 2;
char[] builtHalf = new char[halfLen];
String bestCandidate = null;
for (int pos = 0; pos < halfLen; pos++) {
int tChar = tHalf[pos] - 'a';
// Option A: place char > tHalf[pos] at this pos, fill rest smallest
for (int c = tChar + 1; c < 26; c++) {
if (avail[c] > 0) {
// Use char c at pos
avail[c]--;
builtHalf[pos] = (char) ('a' + c);
// Fill rest with smallest
int[] tempAvail = avail.clone();
char[] tempHalf = builtHalf.clone();
int fill = pos + 1;
for (int cc = 0; cc < 26; cc++)
for (int j = 0; j < tempAvail[cc]; j++)
if (fill < halfLen) tempHalf[fill++] = (char) ('a' + cc);
String candidate = buildPalindrome(tempHalf, mid, n);
if (bestCandidate == null || candidate.compareTo(bestCandidate) < 0)
bestCandidate = candidate;
// Restore
avail[c]++;
break; // smallest such c is best, no need to try larger
}
}
// Option B: place exact tHalf[pos] char and continue matching
if (avail[tChar] > 0) {
avail[tChar]--;
builtHalf[pos] = (char) ('a' + tChar);
// Continue to next position
} else {
// Can't match prefix anymore, stop
break;
}
// If we've matched entire tHalf
if (pos == halfLen - 1) {
// leftHalf == tHalf, palindrome > target only if:
// n is odd AND mid > target[halfLen]
if (n % 2 != 0 && mid > target.charAt(halfLen)) {
String candidate = buildPalindrome(builtHalf, mid, n);
if (bestCandidate == null || candidate.compareTo(bestCandidate) < 0)
bestCandidate = candidate;
}
// Also: leftHalf == tHalf but palindrome's right half is mirror
// Palindrome = leftHalf + [mid] + reverse(leftHalf)
// Compare full palindrome with target
String candidate = buildPalindrome(builtHalf, mid, n);
if (candidate.compareTo(target) > 0) {
if (bestCandidate == null || candidate.compareTo(bestCandidate) < 0)
bestCandidate = candidate;
}
}
}
return bestCandidate != null ? bestCandidate : "";
}
private char[] buildSmallestHalf(int[] freq, int halfLen) {
char[] half = new char[halfLen];
int idx = 0;
for (int i = 0; i < 26; i++)
for (int j = 0; j < freq[i] / 2; j++)
half[idx++] = (char) ('a' + i);
return half;
}
private String buildPalindrome(char[] half, char mid, int n) {
StringBuilder sb = new StringBuilder();
for (char c : half) sb.append(c);
if (n % 2 != 0) sb.append(mid);
for (int i = half.length - 1; i >= 0; i--) sb.append(half[i]);
return sb.toString();
}
}
"""
Problem: LeetCode 3734 - Lexicographically Smallest Palindromic Permutation Greater Than Target
Difficulty: Hard
Language: Python
Author: CodeByTushu
"""
class Solution:
def lexPalindromicPermutation(self, s: str, target: str) -> str:
n = len(s)
freq = [0] * 26
for c in s:
freq[ord(c) - ord("a")] += 1
# Palindrome is possible only if at most 1 character has odd frequency
odd_count = sum(1 for f in freq if f % 2 != 0)
if odd_count > 1:
return ""
# Middle character for odd length
mid = ""
for i in range(26):
if freq[i] % 2 != 0:
mid = chr(ord("a") + i)
break
half_len = n // 2
def build_palindrome(half: list[str]) -> str:
left = "".join(half)
right = "".join(reversed(half))
if n % 2 != 0:
return left + mid + right
return left + right
# Build smallest possible palindrome
smallest_half = []
for i in range(26):
for _ in range(freq[i] // 2):
smallest_half.append(chr(ord("a") + i))
smallest = build_palindrome(smallest_half)
if smallest > target:
return smallest
t_half = target[:half_len]
avail = [f // 2 for f in freq]
built_half = [""] * half_len
best_candidate = None
for pos in range(half_len):
t_char = ord(t_half[pos]) - ord("a")
# Option A: place char > t_half[pos] at this pos, fill rest with smallest
for c in range(t_char + 1, 26):
if avail[c] > 0:
avail[c] -= 1
built_half[pos] = chr(ord("a") + c)
temp_avail = list(avail)
temp_half = list(built_half)
fill = pos + 1
for cc in range(26):
for _ in range(temp_avail[cc]):
if fill < half_len:
temp_half[fill] = chr(ord("a") + cc)
fill += 1
candidate = build_palindrome(temp_half)
if best_candidate is None or candidate < best_candidate:
best_candidate = candidate
avail[c] += 1
break # Smallest such c is best
# Option B: place exact t_half[pos] char and continue matching prefix
if avail[t_char] > 0:
avail[t_char] -= 1
built_half[pos] = chr(ord("a") + t_char)
else:
break
# If we've matched entire t_half
if pos == half_len - 1:
if n % 2 != 0 and mid > target[half_len]:
candidate = build_palindrome(built_half)
if best_candidate is None or candidate < best_candidate:
best_candidate = candidate
candidate = build_palindrome(built_half)
if candidate > target:
if best_candidate is None or candidate < best_candidate:
best_candidate = candidate
return best_candidate if best_candidate is not None else ""
/**
* Problem: LeetCode 3734 - Lexicographically Smallest Palindromic Permutation Greater Than Target
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Problem: LeetCode 3734 - Lexicographically Smallest Palindromic Permutation Greater Than Target
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
string lexPalindromicPermutation(string s, string target) {
int n = s.length();
vector<int> freq(26, 0);
for (char c : s) {
freq[c - 'a']++;
}
// Palindrome possible only if at most 1 odd frequency
int oddCount = 0;
for (int f : freq) {
if (f % 2 != 0) oddCount++;
}
if (oddCount > 1) return "";
// Middle character for odd length
char mid = 0;
for (int i = 0; i < 26; i++) {
if (freq[i] % 2 != 0) {
mid = (char)('a' + i);
break;
}
}
int halfLen = n / 2;
// Build smallest left half
vector<char> smallestHalf;
smallestHalf.reserve(halfLen);
for (int i = 0; i < 26; i++) {
for (int j = 0; j < freq[i] / 2; j++) {
smallestHalf.push_back((char)('a' + i));
}
}
string smallest = buildPalindrome(smallestHalf, mid, n);
if (smallest > target) return smallest;
string tHalf = target.substr(0, halfLen);
vector<int> avail(26, 0);
for (int i = 0; i < 26; i++) avail[i] = freq[i] / 2;
vector<char> builtHalf(halfLen);
string bestCandidate = "";
bool hasCandidate = false;
for (int pos = 0; pos < halfLen; pos++) {
int tChar = tHalf[pos] - 'a';
// Option A: place char > tHalf[pos] at this pos, fill rest smallest
for (int c = tChar + 1; c < 26; c++) {
if (avail[c] > 0) {
avail[c]--;
builtHalf[pos] = (char)('a' + c);
vector<int> tempAvail = avail;
vector<char> tempHalf = builtHalf;
int fill = pos + 1;
for (int cc = 0; cc < 26; cc++) {
for (int j = 0; j < tempAvail[cc]; j++) {
if (fill < halfLen) tempHalf[fill++] = (char)('a' + cc);
}
}
string candidate = buildPalindrome(tempHalf, mid, n);
if (!hasCandidate || candidate < bestCandidate) {
bestCandidate = candidate;
hasCandidate = true;
}
avail[c]++;
break;
}
}
// Option B: place exact tHalf[pos] char and continue matching
if (avail[tChar] > 0) {
avail[tChar]--;
builtHalf[pos] = (char)('a' + tChar);
} else {
break;
}
// If we've matched entire tHalf
if (pos == halfLen - 1) {
if (n % 2 != 0 && mid > target[halfLen]) {
string candidate = buildPalindrome(builtHalf, mid, n);
if (!hasCandidate || candidate < bestCandidate) {
bestCandidate = candidate;
hasCandidate = true;
}
}
string candidate = buildPalindrome(builtHalf, mid, n);
if (candidate > target) {
if (!hasCandidate || candidate < bestCandidate) {
bestCandidate = candidate;
hasCandidate = true;
}
}
}
}
return hasCandidate ? bestCandidate : "";
}
private:
string buildPalindrome(const vector<char>& half, char mid, int n) {
string res;
res.reserve(n);
for (char c : half) res.push_back(c);
if (n % 2 != 0) res.push_back(mid);
for (int i = (int)half.size() - 1; i >= 0; i--) res.push_back(half[i]);
return res;
}
};
/**
* Problem: LeetCode 3734 - Lexicographically Smallest Palindromic Permutation Greater Than Target
* Difficulty: Hard
* Language: JavaScript
* Author: CodeByTushu
*/
var lexPalindromicPermutation = function(s, target) {
const n = s.length;
const freq = new Array(26).fill(0);
const codeA = 97;
for (let i = 0; i < n; i++) freq[s.charCodeAt(i) - codeA]++;
// Palindrome possible only if at most 1 odd frequency
let oddCount = 0;
for (let f of freq) if (f % 2 !== 0) oddCount++;
if (oddCount > 1) return "";
// Middle character for odd length
let mid = "";
for (let i = 0; i < 26; i++) {
if (freq[i] % 2 !== 0) {
mid = String.fromCharCode(codeA + i);
break;
}
}
const halfLen = Math.floor(n / 2);
function buildPalindrome(half, midChar, totalLen) {
let res = half.join("");
if (totalLen % 2 !== 0) res += midChar;
for (let i = half.length - 1; i >= 0; i--) res += half[i];
return res;
}
// Build smallest left half
const smallestHalf = [];
for (let i = 0; i < 26; i++) {
for (let j = 0; j < Math.floor(freq[i] / 2); j++) {
smallestHalf.push(String.fromCharCode(codeA + i));
}
}
const smallest = buildPalindrome(smallestHalf, mid, n);
if (smallest > target) return smallest;
const tHalf = target.substring(0, halfLen);
const avail = new Array(26).fill(0);
for (let i = 0; i < 26; i++) avail[i] = Math.floor(freq[i] / 2);
const builtHalf = new Array(halfLen);
let bestCandidate = null;
for (let pos = 0; pos < halfLen; pos++) {
const tChar = tHalf.charCodeAt(pos) - codeA;
// Option A: place char > tHalf[pos] at this pos, fill rest smallest
for (let c = tChar + 1; c < 26; c++) {
if (avail[c] > 0) {
avail[c]--;
builtHalf[pos] = String.fromCharCode(codeA + c);
const tempAvail = avail.slice();
const tempHalf = builtHalf.slice();
let fill = pos + 1;
for (let cc = 0; cc < 26; cc++) {
for (let j = 0; j < tempAvail[cc]; j++) {
if (fill < halfLen) tempHalf[fill++] = String.fromCharCode(codeA + cc);
}
}
const candidate = buildPalindrome(tempHalf, mid, n);
if (bestCandidate === null || candidate < bestCandidate) {
bestCandidate = candidate;
}
avail[c]++;
break; // smallest such c is best
}
}
// Option B: place exact tHalf[pos] char and continue matching
if (avail[tChar] > 0) {
avail[tChar]--;
builtHalf[pos] = String.fromCharCode(codeA + tChar);
} else {
break;
}
if (pos === halfLen - 1) {
if (n % 2 !== 0 && mid > target[halfLen]) {
const candidate = buildPalindrome(builtHalf, mid, n);
if (bestCandidate === null || candidate < bestCandidate) {
bestCandidate = candidate;
}
}
const candidate = buildPalindrome(builtHalf, mid, n);
if (candidate > target) {
if (bestCandidate === null || candidate < bestCandidate) {
bestCandidate = candidate;
}
}
}
}
return bestCandidate !== null ? bestCandidate : "";
};