Find two unique Palindrome Strings using given String characters
You are given a string S of two distinct characters as input, the task is to find two strings using characters of the given string, such that both strings are different from S and both should be a palindrome.
Input: S = “xyyxxxx”
Output: yxxxxxy, xxyxyxx
Explanation: It can be verified that at least one of the output strings is different from S and both are palindrome.
Output: Not Possible
Approach: Implement the idea below to solve the problem:
The problem is observation based and can be solved via checking parity and frequency of both distinct characters in S. Below are the some observations by which we can conclude some rules. Considered X, Y are the frequencies of two distinct characters in S:
- If the below conditions are satisfied, it can be verified that there will not be any two palindrome strings satisfying given conditions:
- If any of X or Y is equal to 1.
- Both X and Y are Odd.
- Rest of the cases except discussed above will have a guaranteed solution.
- When Both X and Y are even:
Say X = 4, Y = 6 then two possible strings are “aabbbbbbaa” and “bbbaaaabbb” and both are different.
- When either X or Y is odd:
Say X = 3, Y = 6 then two possible strings are “bbbaaabbb” and “abbbabbba“.
Follow the steps mentioned below to implement the idea:
- Check the parity of X and Y i.e., of two distinct characters.
- Output answer according to discussed parities of X and Y above.
Below is the implementation of the above approach.
The original String is: baaaaaab Palindrome String: aaabbaaa baaaaaab The original String is: aaabbbb Palindrome String: bbaaabb abbabba The original String is: aaaaaab Palindrome String: Not Possible
Time Complexity: O(N)
Auxiliary Space: O(1)
Please Login to comment...