Replace '?' in a string such that no two adjacent characters are same
Last Updated :
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: 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:
- 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.
- 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++
// 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;
}
Java
// 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
Python3
# 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
C#
// 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
JavaScript
<script>
// Javascript program for
// the above approach
// Function that replace all '?' with
// lowercase alphabets such that each
// adjacent character is different
function 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 S
let S = "?a?a";
// Function Call
document.write(changeString(S));
// This code is contributed by patel2127
</script>
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(N)
Similar Reads
Rearrange characters in a String such that no two adjacent characters are same
Given a string s with lowercase repeated characters, the task is to rearrange characters in a string so that no two adjacent characters are the same. If it is not possible to do so, then print empty string ("").Note: Multiple valid rearranged strings can be possible for same input string. Examples:
14 min read
Rearrange string such that no pair of adjacent characters are of the same type
Given alphanumeric string str, the task is to rearrange the string such that no two adjacent characters are of the same type, i.e., no two adjacent characters can be alphabets or digits. If no such arrangement is possible, print -1. Examples: Input: str = "geeks2020"Output: g2e0e2k0s Input: str = "I
8 min read
Rearrange characters in a sorted string such that no pair of adjacent characters are the same
Given a sorted string S consisting of N lowercase characters, the task is to rearrange characters in the given string such that no two adjacent characters are the same. If it is not possible to rearrange as per the given criteria, then print "-1". Examples: Input: S = "aaabc"Output: abaca Input: S =
15+ min read
Minimum replacements to make adjacent characters unequal in a ternary string
Given a string of '0', '1' and '2'. The task is to find the minimum number of replacements such that the adjacent characters are not equal. Examples: Input: s = "201220211" Output: 2 Resultant string after changes is 201210210 Input: s = "0120102" Output: 0 Approach: The following problem can be sol
7 min read
Minimum replacements in a string to make adjacent characters unequal
Given a lowercase character string str of size N. In one operation any character can be changed into some other character. The task is to find the minimum number of operations such that no two adjacent characters are equal.Examples: Input: Str = "caaab" Output: 1 Explanation: Change the second a to
6 min read
Minimize swaps of pairs of characters required such that no two adjacent characters in the string are same
Given a string S consisting of N characters, the task is to find the minimum number of pairs of characters that are required to be swapped such that no two adjacent characters are the same. If it is not possible to do so, then print "-1". Examples: Input: S = "ABAACD"Output: 1Explanation: Swapping S
9 min read
Minimum replacements to make adjacent characters unequal in a ternary string | Set-2
Given a string of â0â, â1â, and â2â. The task is to find the minimum number of replacements such that the adjacent characters are not equal. Examples: Input: s = â201220211â Output: 2 Resultant string after changes is 201210210 Input: s = â0120102â Output: 0 Approach: The problem has been solved usi
15+ min read
Number of ways to remove a sub-string from S such that all remaining characters are same
Given a string str consisting only of lowercase English alphabets, the task is to count the number of ways to remove exactly one sub-string from str such that all remaining characters are same. Note: There are at least two different characters in str and we can remove the whole string as well. Examp
7 min read
Quick way to check if all the characters of a string are same
Given a string, check if all the characters of the string are the same or not. Examples: Input : s = "geeks"Output : No Input : s = "gggg" Output : Yes Recommended PracticeCheck StringTry It! Simple Way To find whether a string has all the same characters. Traverse the whole string from index 1 and
8 min read
Remove all duplicate adjacent characters from a string using Stack
Given a string, str, the task is to remove all the duplicate adjacent characters from the given string. Examples: Input: str= âazxxzyâOutput: ay Removal of "xx" modifies the string to âazzyâ. Now, the removal of "zz" modifies the string to âayâ. Since the string âayâ doesn't contain duplicates, the
6 min read