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

16 Jul, 2021
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: babaExplanation: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: acaExplanation: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:
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 1Traverse 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.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 1Print the string after the above steps.
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
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.
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.
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
Print the string after the above steps.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// 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 differentstring 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 Codeint main(){    // Given string S    string S = "?a?a";     // Function Call    cout << changeString(S);     return 0;}
// Java program for// the above approachclass GFG{ // Function that replace all '?' with// lowercase alphabets such that each// adjacent character is differentstatic 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 Codepublic 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
# Python3 program for# the above approach # Function that replace all '?' with# lowercase alphabets such that each# adjacent character is differentdef 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 Codeif __name__ == '__main__':         # Given String S    S = "?a?a"     # Function Call    print(changeString(S)) # This code is contributed by gauravrajput1
// C# program for the above approachusing System;  class GFG{ // Function that replace all '?' with// lowercase alphabets such that each// adjacent character is differentstatic 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 Codepublic static void Main(){     // Given String S  string S = "?a?a";   // Function Call  Console.WriteLine(changeString(S));}} // This code is contributed by sanjoy_62
<script>// Javascript program for// the above approach // Function that replace all '?' with// lowercase alphabets such that each// adjacent character is differentfunction changeString(S){    // Store the given String  let s = S.split("");    let N = S.length;    // If the first character is '?'  if (s[0] == '?')  {    s[0] = 'a';    if (s[0] == s[1])    {      s[0] = String.fromCharCode(s[0].charCodeAt(0)+1);    }  }    // Traverse the String [1, N - 1]  for (let 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] = String.fromCharCode(s[i].charCodeAt(0)+1);      }        // Check equality with      // the next character      if (s[i] == s[i + 1])      {        s[i] = String.fromCharCode(s[i].charCodeAt(0)+1);      }        // Check equality with      // the previous character      if (s[i] == s[i - 1])      {        s[i]=String.fromCharCode(s[i].charCodeAt(0)+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]++;    }  }    let ans = "";      for(let  i = 0; i < s.length; i++)  {    ans += s[i];  }      // Return the resultant String  return ans;} // Driver Code// Given String Slet S = "?a?a"; // Function Calldocument.write(changeString(S)); // This code is contributed by patel2127</script>
baba
Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(N)
 
Rajput-Ji
sanjoy_62
GauravRajput1
patel2127
permutation
Combinatorial
Pattern Searching
Strings
Strings
permutation
Combinatorial
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find the Number of Permutations that satisfy the given condition in an array
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Probability of getting K heads in N coin tosses
Number of handshakes such that a person shakes hands only once
Largest permutation after at most k swaps
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if an URL is valid or not using Regular Expression
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching