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 b≠a at positions (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-palindrome INPUT String s = "abab" a i=0 b i=1 a i=2 b i=3 Anti-palindrome Rule: s[i] != s[n-i-1] Mirror Pairs to Check: (0,3): a != b [OK] (1,2): b != a [OK] Already valid! No swaps needed ALGORITHM STEPS 1 Sort String Sort to get lex smallest base "aabb" 2 Check Middle Pairs If mid chars equal: return -1 s[n/2-1] vs s[n/2] 3 Greedy Swap For each pair (i, n-i-1): swap if s[i] == s[n-i-1] 4 Verify Result Check all pairs different Return lex smallest valid "aabb" --> "abab" FINAL RESULT Anti-palindrome String: a b a b a!=b [OK] b!=a [OK] Output: "abab" Valid Anti-palindrome Lex Smallest: [OK] Key Insight: Sort first for lex smallest, then fix conflicts by swapping. For string "abab", it's already anti-palindromic (a!=b and b!=a). If more than half chars are same, return -1 since middle pair will always conflict. Time: O(n log n) for sorting | Space: O(n) for result string TutorialsPoint - Make String Anti-palindrome | Optimal Greedy Sorting Approach
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