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
Make String Anti-palindromeInputbaca"baca"Process1. Count: a=2, b=1, c=12. Check: max ≤ 2 ✓3. Sort: aabcOutputaabc"aabc"Anti-palindrome condition: s[i] ≠ s[n-1-i] for all iMirror positionsPosition (0,3): a ≠ c ✓Position (1,2): a ≠ b ✓Valid Anti-palindrome!
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
Asked in
Google 25 Amazon 18 Microsoft 15
28.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen