Make the string lexicographically smallest and non palindromic by replacing exactly one character

Given a palindromic string str containing only lowercase letters, the task is to print the lexicographically smallest string, by replacing exactly one character, such the string is not a palindrome.

Examples:

Input: str = “abccba”
Output: “aaccba”
Explanation:
Lexicographically smallest non-palindromic string possible is “aaccba”, here we have replaced the second letter ‘b’ by an ‘a’ which makes it a non palindrome.

Input: str = “a”
Output: -1
Explanation:
A single character is always a palindrome hence we cannot replace the value. Therefore the output is -1.

Approach: To solve the problem mentioned above we will check only half of the string and replace all characters which are not ‘a’ to the character ‘a’ itself. The edge case for the question is if there is only one character, we will return an empty string. Otherwise, if all the characters are the same then we will replace the last character only with character ‘b’.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to make the string
// lexicographically smallest non
// palindromic string by replacing
// exactly one character
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the required string
string findStr(string S)
{
    // length of the string
    int n = S.size();
  
    // Iterate till half of the string
    for (int i = 0; i < n / 2; ++i) {
  
        // replacing a non 'a' char with 'a'
        if (S[i] != 'a') {
            S[i] = 'a';
  
            return S;
        }
    }
  
    // Check if there is no 'a' in string
    // we replace last char of string by 'b'
    S[n - 1] = 'b';
  
    // If the input is a single character
    return n < 2 ? " -1 " : S;
}
  
// Driver code
int main()
{
    string str = "a";
    cout << findStr(str) << endl;
  
    string str1 = "abccba";
    cout << findStr(str1) << endl;
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to make the string
// lexicographically smallest non
// palindromic string by replacing
// exactly one character
import java.util.*;
class GFG {
  
// Function to find the required string
static String findStr(String S)
{
    StringBuilder sb = new StringBuilder(S);
  
    // length of the string
    int n = sb.length();
  
    // Iterate till half of the string
    for (int i = 0; i < n / 2; ++i)
    {
  
        // replacing a non 'a' char with 'a'
        if (sb.charAt(i) != 'a'
        {
            sb.setCharAt(i, 'a');
  
            return sb.toString();
        }
    }
  
    // Check if there is no 'a' in string
    // we replace last char of string by 'b'
    sb.setCharAt(n - 1, 'b');
  
    // If the input is a single character
    return n < 2 ? " -1 " : sb.toString();
}
  
// Driver code
public static void main(String[] args)
{
    String str = "a";
    System.out.println(findStr(str));
  
    String str1 = "abccba";
    System.out.println(findStr(str1));
}
}
  
// This code is contributed by offbeat

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to make the string 
# lexicographically smallest non 
# palindromic string by replacing 
# exactly one character 
  
# Function to find the required string 
def findStr(S):
      
    S = list(S)
      
    # Length of the string 
    n = len(S)
      
    # Iterate till half of the string 
    for i in range(0, n // 2):
          
        # Replacing a non 'a' char with 'a' 
        if S[i] != 'a':
            S[i] = 'a'
            return (''.join(S))
      
    # Check if there is no 'a' in string 
    # we replace last char of string by 'b' 
    S[n - 1] = 'b'
      
    # If the input is a single character 
    if n < 2:
        return '-1'
    else:
        return (''.join(S))
      
# Driver Code 
if __name__=='__main__':
      
    str1 = 'a'
    print(findStr(str1))
      
    str2 = 'abccba'
    print(findStr(str2))
  
# This code is contributed by rutvik_56

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to make the string
// lexicographically smallest non
// palindromic string by replacing
// exactly one character
using System;
  
class GFG{
  
// Function to find the required string
static String findStr(char []S)
{
  
    // Length of the string
    int n = S.Length;
  
    // Iterate till half of the string
    for(int i = 0; i < n / 2; ++i)
    {
         
       // Replacing a non 'a' char with 'a'
       if (S[i] != 'a')
       {
           S[i] = 'a';
           return new String(S);
       }
    }
  
    // Check if there is no 'a' in string
    // we replace last char of string by 'b'
    S[n - 1] = 'b';
  
    // If the input is a single character
    return n < 2 ? " -1 " : new String(S);
}
  
// Driver code
public static void Main(String[] args)
{
    String str = "a";
    Console.WriteLine(findStr(str.ToCharArray()));
  
    String str1 = "abccba";
    Console.WriteLine(findStr(str1.ToCharArray()));
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

-1 
aaccba

Time Complexity: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : offbeat, rutvik_56, 29AjayKumar