Replace ‘?’ in a string such that no two adjacent characters are same

Given a string S of length N consisting of “?” and lowercase letters, the task is to replace “?” with lowercase letters such that no adjacent characters are the same. If more than one possible combination exists, print any one of them.

Examples:

Input: S = “?a?a”
Output: baba
Explanation:
Replacing all ‘?’s with ‘b’ modifies the string to “baba”.
Since no adjacent characters in “baba” are the same, print the string as the answer.

Input: S = “???”
Output: aca
Explanation:
Replace first ‘?’ with ‘a’.
Replace second ‘?’ with ‘c’.
Replace third ‘?’ with ‘a’. Now, the modified string is “aca”.
Therefore, there are no adjacent characters in “ca” which are same.

Naive Approach: The simplest approach is to try generating all possible permutations of the given string consisting of lowercase letters. There can be 26N strings. In each of these strings, check whether adjacent characters matches or not and all lowercase characters in the given string matches the chosen permutation of the string. 



Time Complexity: O(N*26N), where N is the length of the given string.
Auxiliary Space: O(N)

Efficient Approach: To optimize the above approach, the idea is to replace every ‘?’ by the character ‘a’ and check if this character is equal to the adjacent character or not. If it is equal to the adjacent character then increment the current character. Below are the steps:

  1. If the first character of the string is ‘?’ then replace it with ‘a’ and if it is equal to the next character then increment the current character by 1
  2. Traverse the given string using a variable i over the range [1, N – 1] and if the current character is ‘?’ and do the following:
    • Update character at index i as s[i] = ‘a’.
    • Now if the character at index i and (i – 1) are the same then increment the current character by 1.
    • Now if the character at index i and (i + 1) are the same then increment the current character by 1.
    • Now if the character at index i and (i – 1) are the same again, then increment the current character by 1. This step is mandatory because after increment character in the above step it might be possible character at index i and  (i – 1) are the same.
  3. If the last character of the string is ‘?’ then replace it with ‘a’ and if it is equal to the previous character then increment the last character by 1
  4. Print the string after the above steps.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include "bits/stdc++.h"
using namespace std;
 
// Function that replace all '?' with
// lowercase alphabets such that each
// adjacent character is different
string changeString(string S)
{
    // Store the given string
    string s = S;
 
    int N = (int)s.length();
 
    // If the first character is '?'
    if (s[0] == '?') {
        s[0] = 'a';
        if (s[0] == s[1]) {
            s[0]++;
        }
    }
 
    // Traverse the string [1, N - 1]
    for (int i = 1; i < N - 1; i++) {
 
        // If the current character is '?'
        if (s[i] == '?') {
 
            // Change the character
            s[i] = 'a';
 
            // Check equality with
            // the previous character
            if (s[i] == s[i - 1]) {
                s[i]++;
            }
 
            // Check equality with
            // the next character
            if (s[i] == s[i + 1]) {
                s[i]++;
            }
 
            // Check equality with
            // the previous character
            if (s[i] == s[i - 1]) {
                s[i]++;
            }
        }
    }
 
    // If the last character is '?'
    if (s[N - 1] == '?') {
 
        // Change character
        s[N - 1] = 'a';
 
        // Check with previous character
        if (s[N - 1] == s[N - 2]) {
            s[N - 1]++;
        }
    }
 
    // Return the resultant string
    return s;
}
 
// Driver Code
int main()
{
    // Given string S
    string S = "?a?a";
 
    // Function Call
    cout << changeString(S);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for
// the above approach
class GFG{
 
// Function that replace all '?' with
// lowercase alphabets such that each
// adjacent character is different
static String changeString(String S)
{
  // Store the given String
  char []s = S.toCharArray();
 
  int N = (int)S.length();
 
  // If the first character is '?'
  if (s[0] == '?')
  {
    s[0] = 'a';
    if (s[0] == s[1])
    {
      s[0]++;
    }
  }
 
  // Traverse the String [1, N - 1]
  for (int i = 1; i < N - 1; i++)
  {
    // If the current
    // character is '?'
    if (s[i] == '?')
    {
      // Change the character
      s[i] = 'a';
 
      // Check equality with
      // the previous character
      if (s[i] == s[i - 1])
      {
        s[i]++;
      }
 
      // Check equality with
      // the next character
      if (s[i] == s[i + 1])
      {
        s[i]++;
      }
 
      // Check equality with
      // the previous character
      if (s[i] == s[i - 1])
      {
        s[i]++;
      }
    }
  }
 
  // If the last character is '?'
  if (s[N - 1] == '?')
  {
    // Change character
    s[N - 1] = 'a';
 
    // Check with previous
    // character
    if (s[N - 1] == s[N - 2])
    {
      s[N - 1]++;
    }
  }
 
  String ans = "";
   
  for(int  i = 0; i < s.length; i++)
  {
    ans += s[i];
  }
   
  // Return the resultant String
  return ans;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given String S
  String S = "?a?a";
 
  // Function Call
  System.out.print(changeString(S));
}
}
 
// This code is contributed by Rajput-Ji
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for
# the above approach
 
# Function that replace all '?' with
# lowercase alphabets such that each
# adjacent character is different
def changeString(S):
     
    # Store the given String
    N = len(S)
    s = [' '] * (len(S))
     
    for i in range(len(S)):
        s[i] = S[i]
 
    # If the first character is '?'
    if (s[0] == '?'):
        s[0] = 'a'
         
        if (s[0] == s[1]):
            s[0] = chr(ord(s[0]) + 1)
 
    # Traverse the String [1, N - 1]
    for i in range(1, N - 1):
         
        # If the current
        # character is '?'
        if (s[i] == '?'):
             
            # Change the character
            s[i] = 'a'
 
            # Check equality with
            # the previous character
            if (s[i] == s[i - 1]):
                s[i] =  chr(ord(s[i]) + 1)
 
            # Check equality with
            # the next character
            if (s[i] == s[i + 1]):
                s[i] =  chr(ord(s[i]) + 1)
 
            # Check equality with
            # the previous character
            if (s[i] == s[i - 1]):
                s[i] =  chr(ord(s[i]) + 1)
 
    # If the last character is '?'
    if (s[N - 1] == '?'):
         
        # Change character
        s[N - 1] = 'a'
         
        # Check with previous
        # character
        if (s[N - 1] == s[N - 2]):
            s[N - 1] += 1
 
    ans = ""
    for i in range(len(s)):
        ans += s[i]
         
    # Return the resultant String
    return ans
 
# Driver Code
if __name__ == '__main__':
     
    # Given String S
    S = "?a?a"
 
    # Function Call
    print(changeString(S))
 
# This code is contributed by gauravrajput1
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
  
class GFG{
 
// Function that replace all '?' with
// lowercase alphabets such that each
// adjacent character is different
static string changeString(string S)
{
   
  // Store the given String
  char []s = S.ToCharArray();
   
  int N = S.Length;
 
  // If the first character is '?'
  if (s[0] == '?')
  {
    s[0] = 'a';
    if (s[0] == s[1])
    {
      s[0]++;
    }
  }
 
  // Traverse the String [1, N - 1]
  for(int i = 1; i < N - 1; i++)
  {
     
    // If the current
    // character is '?'
    if (s[i] == '?')
    {
       
      // Change the character
      s[i] = 'a';
 
      // Check equality with
      // the previous character
      if (s[i] == s[i - 1])
      {
        s[i]++;
      }
 
      // Check equality with
      // the next character
      if (s[i] == s[i + 1])
      {
        s[i]++;
      }
 
      // Check equality with
      // the previous character
      if (s[i] == s[i - 1])
      {
        s[i]++;
      }
    }
  }
 
  // If the last character is '?'
  if (s[N - 1] == '?')
  {
     
    // Change character
    s[N - 1] = 'a';
 
    // Check with previous
    // character
    if (s[N - 1] == s[N - 2])
    {
      s[N - 1]++;
    }
  }
 
  string ans = "";
   
  for(int  i = 0; i < s.Length; i++)
  {
    ans += s[i];
  }
   
  // Return the resultant String
  return ans;
}
 
// Driver Code
public static void Main()
{
   
  // Given String S
  string S = "?a?a";
 
  // Function Call
  Console.WriteLine(changeString(S));
}
}
 
// This code is contributed by sanjoy_62
chevron_right

Output
baba







Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: 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.




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.



Article Tags :