Make String Anti-Palindrome – GeeksforGeeks
Given a string S of length N is said to be an Anti-palindrome string if, for each 0 ≤ i ≤ N-1, Si != S(N – 1 − i). The task is to print Anti-Palindrome String formed, If it is not possible to find print “-1”
Examples:
Input: S = “abdcccdb”
Output: “cbbaccdd”
Explanation: cbbaccdd is an Anti-palindrome string as for each 0 ≤ i ≤ N-1, Si != S(N-1−i).Input: s = “xyz”
Output: -1
Approach: The problem can be solved based on the following idea:
If the length of the string S is odd, Then the answer is always “-1” as the condition fails on the middle element. Count the frequency of each character in the string S, if any character frequency is more than half the length of the string, then also the condition fails. Otherwise, print the string having characters continuously up to their respective frequencies.
Follow the below steps to implement the idea:
- Check the length of the string, If it is odd print “-1“.
- Else, count the frequency of each character using the map.
- If any character frequency is more than half of the string S length, print “-1”.
- Else, print the string having characters continuously up to their respective frequencies.
Below is the implementation of the above approach.
C++
|
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Related Articles:
Given a string S of length N is said to be an Anti-palindrome string if, for each 0 ≤ i ≤ N-1, Si != S(N – 1 − i). The task is to print Anti-Palindrome String formed, If it is not possible to find print “-1”
Examples:
Input: S = “abdcccdb”
Output: “cbbaccdd”
Explanation: cbbaccdd is an Anti-palindrome string as for each 0 ≤ i ≤ N-1, Si != S(N-1−i).Input: s = “xyz”
Output: -1
Approach: The problem can be solved based on the following idea:
If the length of the string S is odd, Then the answer is always “-1” as the condition fails on the middle element. Count the frequency of each character in the string S, if any character frequency is more than half the length of the string, then also the condition fails. Otherwise, print the string having characters continuously up to their respective frequencies.
Follow the below steps to implement the idea:
- Check the length of the string, If it is odd print “-1“.
- Else, count the frequency of each character using the map.
- If any character frequency is more than half of the string S length, print “-1”.
- Else, print the string having characters continuously up to their respective frequencies.
Below is the implementation of the above approach.
C++
|
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Related Articles: