![]() |
VOOZH | about |
Given two strings A and B of length N which contains only lowercase characters, find the lexicographically largest string C of length N which contains only lowercase characters such that the following conditions are satisfied.
Examples:
Input: N = 3, A = "aba", B = "ade"
Output: ada
Explanation: "ada" is lexicographically greater than the string A and lexicographically smaller than the string B and it is a palindrome.Input: N = 1, A = "z", B = "z"
Output: -1
Approach: The idea behind the following approach is:
This problem can be solved with the some observations. Our goal is to make palindrome and it should be lexicographically larger than A but smaller than B. We will perform operations on string B. Divide B to half string and add first half to C, add a middle character (when N is odd) and again add first half to C but in reverse order. Now, to make it smaller than B and greater than A, we will change characters in C accordingly.
Below are the steps involved in the implementation of the code:
Below is the implementation of the code:
awzwa
Time Complexity: O(N), where N is the length of strings A and B
Auxiliary Space: O(N)