Make String Anti-palindrome - Problem
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".
Input & Output
Example 1 — Basic Case
$
Input:
s = "abab"
›
Output:
"abab"
💡 Note:
The string "abab" is already an anti-palindrome: a≠b at positions (0,3) and (1,2), so no swaps needed.
Example 2 — Need Rearrangement
$
Input:
s = "baca"
›
Output:
"aabc"
💡 Note:
Sort to get "aabc": positions (0,3) have a≠c and positions (1,2) have a≠b, making it a valid anti-palindrome.
Example 3 — Impossible Case
$
Input:
s = "aaaa"
›
Output:
"-1"
💡 Note:
All characters are the same, so it's impossible to make any position different from its mirror position.
Constraints
- 2 ≤ s.length ≤ 105
- s.length is even
- s consists of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
String s that needs to become anti-palindrome
2
Process
Check feasibility and sort for optimal arrangement
3
Output
Lexicographically smallest anti-palindrome or -1
Key Takeaway
🎯 Key Insight: If any character appears more than half the time, anti-palindrome is impossible - otherwise sort for optimal result
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code