VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-the-largest-palindromic-string-which-lies-between-two-other-strings/

⇱ Construct the Largest Palindromic String which lies between two other Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct the Largest Palindromic String which lies between two other Strings

Last Updated : 16 Nov, 2023

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.

  • C should be lexicographically greater than the string A.
  • C should be lexicographically smaller than the string B.
  • C should be palindrome.

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:

  • Check A should be smaller than B otherwise return -1.
  • Create a empty string ans representing C.
  • Split B into two halves and add first half to ans, add a middle character (when N is odd) and again first half of B in backward direction.
  • Now, to make it greater than A and smaller than B.
  • Iterate in it and try changing character (on both sides) one by one through i and j variables.
  • If character present at ans[i] and ans[j] is 'a' skip it.
  • If not reduce it by one both the ans[i] and ans[j] and make the characters between i and j index of ans as 'z'. As our goal is to make lexicographically largest.
  • If ans > A and ans < B, return ans.
  • Otherwise "-1".

Below is the implementation of the code:


Output
awzwa

Time Complexity: O(N), where N is the length of strings A and B
Auxiliary Space: O(N)

Comment