Make String Anti-palindrome Problem
Description
LeetCode Problem 3088.
We call a string s of even length n an anti-palindrome if for each index 0 <= i < n, s[i] != s[n - i - 1].
Given a string s, your task is to make s an anti-palindrome by doing any number of operations (including zero).
In one operation, you can select two characters from s and swap them.
Return the resulting string. If multiple strings meet the conditions, return the lexicographically smallest one. If it can't be made into an anti-palindrome, return "-1".
Example 1:
Input: s = "abca"
Output: "aabc"
Explanation:
"aabc" is an anti-palindrome string since s[0] != s[3] and s[1] != s[2]. Also, it is a rearrangement of "abca".
Example 2:
Input: s = "abba"
Output: "aabb"
Explanation:
"aabb" is an anti-palindrome string since s[0] != s[3] and s[1] != s[2]. Also, it is a rearrangement of "abba".
Example 3:
Input: s = "cccd"
Output: "-1"
Explanation:
You can see that no matter how you rearrange the characters of "cccd", either s[0] == s[3] or s[1] == s[2]. So it can not form an anti-palindrome string.
Constraints:
2 <= s.length <= 10^5s.length % 2 == 0sconsists only of lowercase English letters.
Solution
Approach: Greedy + Sorting
Sort the string; this is the smallest arrangement, and it is only a problem if it is a palindrome at the middle. Let m = n / 2. If s[m] != s[m - 1], the sorted string is already an anti-palindrome.
Otherwise, find the first index i >= m whose character differs from s[m - 1] (it is the next larger letter). Walk j from m while s[j] == s[n - j - 1], and each time swap s[j] with s[i] and move both forward. If i runs past the end, no arrangement works and the answer is "-1".
Complexity: O(n log n) time, O(n) space.
class Solution:
def makeAntiPalindrome(self, s: str) -> str:
cs = sorted(s)
n = len(cs)
m = n // 2
if cs[m] == cs[m - 1]:
i = m
while i < n and cs[i] == cs[i - 1]:
i += 1
j = m
while j < n and cs[j] == cs[n - j - 1]:
if i >= n:
return "-1"
cs[i], cs[j] = cs[j], cs[i]
i, j = i + 1, j + 1
return "".join(cs)