Given a string S consisting of lowercase characters, the task is to find the minimum number of swaps required in the string such that S[i] != S[n-i+1], where 1 <= i <= n.
Examples:
Input: N = 3, S = “ABC”
Output: -1
Explanation: In the string “abc” , s[2] = s[3-2+1] even after applying the allowed operation.Input: N = 10, S = “taarrrataa”
Output: 1
Explanation: It is enough to swap the 2nd and 5th characters of the string “taarrrataa” and the new string “trararataa” satisfies the given condition.
Approach: To solve the problem follow the below idea:
If the string has an odd number of letters, you can’t make any solution. This is because there will always be a middle letter that can’t be paired with anything else. If the string has an even number of letters, you have to do some operations
Below are steps to solve the problem:
- Two vectors p and x are initialized, each with 26 elements, to keep track of symmetric pairs and character occurrences.
-
Iterate through the first half of the input String:
- If a character is the same at symmetric positions within the string, it increments the count for that character’s symmetric pair (p vector).
- It also increments the overall count of that character (x vector).
- Then check if any character appears more than half the total characters (N/2). If so, it’s not possible to make an anti-palindrome, and -1 is printed.
- Calculate the total count of symmetric pairs (count) and the maximum count of symmetric pairs (maxi).
Below is the implementation of the above approach:
// C++ code for the above approach: #include <bits/stdc++.h> using namespace std;
typedef long long ll;
bool comp(vector<ll>& a, vector<ll>& b)
{ ll x = a.size(), y = b.size();
return x < y;
} // Function to solve the problem void solve(ll n, string s)
{ // Check if the length of
// the string is odd
if (n % 2) {
// Can't make anti-palindrome
// with odd length
cout << -1 << endl;
}
else {
// Vectors to count symmetric pairs
// and character occurrences
vector<ll> p(26, 0), x(26, 0);
// Iterate over the first
// half of the string
for (ll i = 0; i < n; i++) {
// Count symmetric pairs
if (i < n / 2 && s[i] == s[n - 1 - i])
p[s[i] - 'a' ]++;
// Count all character occurrences
x[s[i] - 'a' ]++;
}
for (ll i = 0; i < 26; i++) {
if (x[i] > n / 2) {
cout << -1 << endl;
// Not possible to make
// anti-palindrome
return ;
}
}
ll coun = 0, maxi = 0;
// Calculate total symmetric
// pairs and maximum symmetric
// pair count
for (ll i = 0; i < 26; i++) {
coun += p[i];
maxi = max(maxi, p[i]);
}
// Calculate answer based on either
// maxi or (coun + 1)/2
cout << max(maxi, (coun + 1) / 2) << endl;
}
} // Driver Code int main()
{ ll N = 10;
string S = "dcbdbdcccc" ;
// Call the solve function
// to find theminimum swaps needed
solve(N, S);
return 0;
} |
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int N = 10 ;
String S = "dcbdbdcccc" ;
// Call the solve function
// to find the minimum swaps needed
solve(N, S);
}
public static void solve( int n, String s) {
// Check if the length of the string is odd
if (n % 2 != 0 ) {
// Can't make anti-palindrome with odd length
System.out.println(- 1 );
} else {
// Arrays to count symmetric pairs and character occurrences
int [] p = new int [ 26 ];
int [] x = new int [ 26 ];
// Iterate over the first half of the string
for ( int i = 0 ; i < n; i++) {
// Count symmetric pairs
if (i < n / 2 && s.charAt(i) == s.charAt(n - 1 - i))
p[s.charAt(i) - 'a' ]++;
// Count all character occurrences
x[s.charAt(i) - 'a' ]++;
}
for ( int i = 0 ; i < 26 ; i++) {
if (x[i] > n / 2 ) {
System.out.println(- 1 );
// Not possible to make anti-palindrome
return ;
}
}
int coun = 0 , maxi = 0 ;
// Calculate total symmetric pairs and maximum symmetric pair count
for ( int i = 0 ; i < 26 ; i++) {
coun += p[i];
maxi = Math.max(maxi, p[i]);
}
// Calculate answer based on either maxi or (coun + 1)/2
System.out.println(Math.max(maxi, (coun + 1 ) / 2 ));
}
}
} |
def solve(n, s):
# Check if the length of the string is odd
if n % 2 :
# Can't make anti-palindrome with odd length
print ( - 1 )
else :
# Lists to count symmetric pairs and character occurrences
p = [ 0 ] * 26
x = [ 0 ] * 26
# Iterate over the first half of the string
for i in range (n):
# Count symmetric pairs
if i < n / / 2 and s[i] = = s[n - 1 - i]:
p[ ord (s[i]) - ord ( 'a' )] + = 1
# Count all character occurrences
x[ ord (s[i]) - ord ( 'a' )] + = 1
for i in range ( 26 ):
if x[i] > n / / 2 :
print ( - 1 )
return
coun = 0
maxi = 0
# Calculate total symmetric pairs and maximum symmetric pair count
for i in range ( 26 ):
coun + = p[i]
maxi = max (maxi, p[i])
# Calculate answer based on either maxi or (coun + 1) // 2
print ( max (maxi, (coun + 1 ) / / 2 ))
# Driver Code if __name__ = = "__main__" :
N = 10
S = "dcbdbdcccc"
# Call the solve function to find the minimum swaps needed
solve(N, S)
#Contributed by Aditi Tyagi |
// C# code for the above approach using System;
public class GFG {
public static void solve( int n, string s)
{
// Check if the length of the string is odd
if (n % 2 != 0) {
// Can't make anti-palindrome with odd length
Console.WriteLine(-1);
}
else {
// Arrays to count symmetric pairs and character
// occurrences
int [] p = new int [26];
int [] x = new int [26];
// Iterate over the first half of the string
for ( int i = 0; i < n; i++) {
// Count symmetric pairs
if (i < n / 2 && s[i] == s[n - 1 - i])
p[s[i] - 'a' ]++;
// Count all character occurrences
x[s[i] - 'a' ]++;
}
for ( int i = 0; i < 26; i++) {
if (x[i] > n / 2) {
Console.WriteLine(-1);
// Not possible to make anti-palindrome
return ;
}
}
int coun = 0, maxi = 0;
// Calculate total symmetric pairs and maximum
// symmetric pair count
for ( int i = 0; i < 26; i++) {
coun += p[i];
maxi = Math.Max(maxi, p[i]);
}
// Calculate answer based on either maxi or
// (coun + 1)/2
Console.WriteLine(
Math.Max(maxi, (coun + 1) / 2));
}
}
public static void Main()
{
int N = 10;
string S = "dcbdbdcccc" ;
// Call the solve function
// to find the minimum swaps needed
solve(N, S);
}
} // This code is contributed by ragul21 |
<script> // JavaScript code for the above approach // Comparator function for sorting vectors function comp(a, b) {
let x = a.length,
y = b.length;
return x < y;
} // Function to solve the problem function solve(n, s) {
// Check if the length of the string is odd
if (n % 2) {
// Can't make anti-palindrome with odd length
document.write(-1);
} else {
// Vectors to count symmetric pairs and character occurrences
let p = new Array(26).fill(0); // symmetric pairs
let x = new Array(26).fill(0); // character occurrences
// Iterate over the first half of the string
for (let i = 0; i < n; i++) {
// Count symmetric pairs
if (i < n / 2 && s[i] === s[n - 1 - i]) p[s[i].charCodeAt() - 97]++;
// Count all character occurrences
x[s[i].charCodeAt() - 97]++;
}
// Check if characters exceed half the string length
for (let i = 0; i < 26; i++) {
if (x[i] > n / 2) {
document.write(-1); // Not possible to make anti-palindrome
return ;
}
}
let coun = 0,
maxi = 0;
// Calculate total symmetric pairs and maximum symmetric pair count
for (let i = 0; i < 26; i++) {
coun += p[i];
maxi = Math.max(maxi, p[i]);
}
// Calculate answer based on either maxi or (coun + 1)/2
document.write(Math.max(maxi, Math.floor((coun + 1) / 2)));
}
} // Driver Code let N = 10; let S = "dcbdbdcccc" ;
// Call the solve function to find the minimum swaps needed solve(N, S); // This code is contributed by Susobhan Akhuli </script> |
1
Time Complexity: O(N)
Auxiliary Space: O(1)