Lexicographically Smallest Palindromic Permutation Greater Than Target Problem
Description
LeetCode Problem 3734.
You are given two strings s and target, each of length n, consisting of lowercase English letters.
Return the lexicographically smallest string that is both a palindromic permutation of s and strictly greater than target. If no such permutation exists, return an empty string.
Example 1:
Input: s = "baba", target = "abba"
Output: "baab"
Explanation:
- The palindromic permutations of s (in lexicographical order) are "abba" and "baab".
- The lexicographically smallest permutation that is strictly greater than target is "baab".
Example 2:
Input: s = "baba", target = "bbaa"
Output: ""
Explanation:
- The palindromic permutations of s (in lexicographical order) are "abba" and "baab".
- None of them is lexicographically strictly greater than target. Therefore, the answer is "".
Example 3:
Input: s = "abc", target = "abb"
Output: ""
Explanation:
s has no palindromic permutations. Therefore, the answer is "".
Example 4:
Input: s = "aac", target = "abb"
Output: "aca"
Explanation:
- The only palindromic permutation of s is "aca".
- "aca" is strictly greater than target. Therefore, the answer is "aca".
Constraints:
1 <= n == s.length == target.length <= 300sandtargetconsist of only lowercase English letters.
Solution
Approach: Greedy on the Left Half
A palindrome is fixed by its left half and at most one centre character. Count the letters of s: if more than one letter has an odd count, no palindromic permutation exists and the answer is "". Otherwise the centre is that odd letter (if any), and the left half uses half of every count.
We want the smallest palindrome strictly greater than target, so we build the left half like a "next permutation":
- Follow the first half of
targetas long as the letters are still available. Letmatchedbe how many letters we could follow. - If the whole half was followed, mirror it (adding the centre) and check whether the result is greater than
target; if so, it is the answer. - Otherwise try to deviate from
targetas late as possible: for each positionposfrom the last followed position down to0, keeptarget's firstposletters, place a letter larger thantarget's letter atpos(the smallest available one first), and fill the rest of the half with the remaining letters in sorted order. Mirror it, and return the first palindrome that is greater thantarget.
If nothing works, return "".
Complexity: time O(n^2 + 26 n) in the worst case (each of up to n / 2 positions rebuilds a half in O(n)), space O(n).
class Solution:
def lexPalindromicPermutation(self, s: str, target: str) -> str:
def build(left: str, middle: str, n: int) -> str:
right = left[::-1]
if n % 2:
return left + middle + right
return left + right
n = len(s)
freq = [0] * 26
for c in s:
freq[ord(c) - 97] += 1
odd = 0
middle = ""
for i, v in enumerate(freq):
if v % 2:
odd += 1
middle = chr(97 + i)
if odd > 1:
return ""
half = [v // 2 for v in freq]
half_len = n // 2
target_half = target[:half_len]
remaining = half[:]
prefix = []
matched = 0
for i in range(half_len):
x = ord(target_half[i]) - 97
if remaining[x] == 0:
break
prefix.append(target_half[i])
remaining[x] -= 1
matched += 1
if matched == half_len:
cand = build("".join(prefix), middle, n)
if cand > target:
return cand
last = half_len - 1 if matched == half_len else matched
for pos in range(last, -1, -1):
rem = half[:]
valid = True
for i in range(pos):
x = ord(target_half[i]) - 97
if rem[x] == 0:
valid = False
break
rem[x] -= 1
if not valid:
continue
target_char = ord(target_half[pos]) - 97
for c in range(target_char + 1, 26):
if rem[c] == 0:
continue
left = target_half[:pos] + chr(97 + c)
rem[c] -= 1
for x in range(26):
left += chr(97 + x) * rem[x]
rem[x] = 0
cand = build(left, middle, n)
if cand > target:
return cand
rem = half[:]
for i in range(pos):
rem[ord(target_half[i]) - 97] -= 1
return ""