Replace all occurrences of string AB with C without using extra space
Last Updated :
30 Apr, 2024
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str.
Examples:
Input : str = "helloABworld"
Output : str = "helloCworld"
Input : str = "fghABsdfABysu"
Output : str = "fghCsdfCysu"
A simple solution is to find all occurrences of “AB”. For every occurrence, replace it with C and move all characters one position back.
Implementation:
C++
// C++ program to replace all occurrences of "AB"
// with "C"
#include <bits/stdc++.h>
void translate(char* str)
{
if (str[0] == '\0')
return;
// Start traversing from second character
for (int i=1; str[i] != '\0'; i++)
{
// If previous character is 'A' and
// current character is 'B"
if (str[i-1]=='A' && str[i]=='B')
{
// Replace previous character with
// 'C' and move all subsequent
// characters one position back
str[i-1] = 'C';
for (int j=i; str[j]!='\0'; j++)
str[j] = str[j+1];
}
}
return;
}
// Driver code
int main()
{
char str[] = "helloABworldABGfG";
translate(str);
printf("The modified string is :\n");
printf("%s", str);
}
Java
// Java program to replace all
// occurrences of "AB" with "C"
import java.io.*;
class GFG {
static void translate(char str[])
{
// Start traversing from second character
for (int i = 1; i < str.length; i++)
{
// If previous character is 'A' and
// current character is 'B"
if (str[i - 1] == 'A' && str[i] == 'B')
{
// Replace previous character with
// 'C' and move all subsequent
// characters one position back
str[i - 1] = 'C';
int j;
for (j = i; j < str.length - 1; j++)
str[j] = str[j + 1];
str[j] = ' ';
}
}
return;
}
// Driver code
public static void main(String args[])
{
String st = "helloABworldABGfG";
char str[] = st.toCharArray();
translate(str);
System.out.println("The modified string is :");
System.out.println(str);
}
}
// This code is contributed by Nikita Tiwari.
Python3
# Python 3 program to replace all
# occurrences of "AB" with "C"
def translate(st) :
# Start traversing from second character
for i in range(1, len(st)) :
# If previous character is 'A'
# and current character is 'B"
if (st[i - 1] == 'A' and st[i] == 'B') :
# Replace previous character with
# 'C' and move all subsequent
# characters one position back
st[i - 1] = 'C'
for j in range(i, len(st) - 1) :
st[j] = st[j + 1]
st[len(st) - 1] = ' '
return
# Driver code
st = list("helloABworldABGfG")
translate(st)
print("The modified string is :")
print(''.join(st))
# This code is contributed by Nikita Tiwari.
C#
// C# program to replace all
// occurrences of "AB" with "C"
using System;
class GFG {
static void translate(char []str)
{
// Start traversing from second character
for (int i = 1; i < str.Length; i++)
{
// If previous character is 'A' and
// current character is 'B"
if (str[i - 1] == 'A' && str[i] == 'B')
{
// Replace previous character with
// 'C' and move all subsequent
// characters one position back
str[i - 1] = 'C';
int j;
for (j = i; j < str.Length - 1; j++)
str[j] = str[j + 1];
str[j] = ' ';
}
}
return;
}
// Driver code
public static void Main()
{
String st = "helloABworldABGfG";
char []str = st.ToCharArray();
translate(str);
Console.WriteLine("The modified string is :");
Console.Write(str);
}
}
// This code is contributed by Nitin Mittal.
JavaScript
<script>
// Javascript program to replace all
// occurrences of "AB" with "C"
function translate(str)
{
// Start traversing from second character
for(let i = 1; i < str.length; i++)
{
// If previous character is 'A' and
// current character is 'B"
if (str[i - 1] == 'A' && str[i] == 'B')
{
// Replace previous character with
// 'C' and move all subsequent
// characters one position back
str[i - 1] = 'C';
let j;
for(j = i; j < str.length - 1; j++)
str[j] = str[j + 1];
str[j] = ' ';
}
}
return;
}
// Driver code
let st = "helloABworldABGfG";
let str = st.split("");
translate(str);
document.write("The modified string is :<br>");
document.write(str.join(""));
// This code is contributed by avanitrachhadiya2155
</script>
PHP
<?php
// PHP program to replace all
// occurrences of "AB" with "C"
function translate(&$str)
{
if ($str[0] == '')
return;
// Start traversing from second character
for ($i = 1; $i < strlen($str); $i++)
{
// If previous character is 'A' and
// current character is 'B"
if ($str[$i - 1] == 'A' && $str[$i] == 'B')
{
// Replace previous character with
// 'C' and move all subsequent
// characters one position back
$str[$i - 1] = 'C';
for ($j = $i; $j < strlen($str) ; $j++)
$str[$j] = $str[$j + 1];
}
}
return;
}
// Driver code
$str = "helloABworldABGfG";
translate($str);
echo "The modified string is :\n";
echo $str;
// This code is contributed
// by ChitraNayal
?>
Output :
The modified string is :
helloCworldCGfG
Time Complexity : O(n2)
Auxiliary Space : O(1)
An efficient solution is to keep track of two indexes, one for modified string (i in below code) and other for original string (j in below code). If we find “AB” at current index j, we increment j by 2 and i by 1. Otherwise, we increment both and copy character from j to i.
Below is implementation of above idea.
C++
// Efficient C++ program to replace all occurrences
// of "AB" with "C"
#include <bits/stdc++.h>
using namespace std;
void translate(string &str)
{
int len = str.size();
if (len < 2)
return;
// Index in modified string
int i = 0;
// Index in original string
int j = 0;
// Traverse string
while (j < len - 1) {
// Replace occurrence of "AB" with "C"
if (str[j] == 'A' && str[j + 1] == 'B') {
// Increment j by 2
j = j + 2;
str[i++] = 'C';
continue;
}
str[i++] = str[j++];
}
if (j == len - 1)
str[i++] = str[j];
// add a null character to terminate string
str[i] = ' ';
str[len - 1] = ' ';
}
// Driver code
int main()
{
string str = "helloABworldABGfG";
translate(str);
cout << "The modified string is:" << endl << str;
}
Java
// Efficient Java program to replace
// all occurrences of "AB" with "C"
import java.io.*;
class GFG {
static void translate(char str[])
{
int len = str.length;
if (len < 2)
return;
// Index in modified string
int i = 0;
// Index in original string
int j = 0;
// Traverse string
while (j < len - 1)
{
// Replace occurrence of "AB" with "C"
if (str[j] == 'A' && str[j + 1] == 'B')
{
// Increment j by 2
j = j + 2;
str[i++] = 'C';
continue;
}
str[i++] = str[j++];
}
if (j == len - 1)
str[i++] = str[j];
// add a null character to terminate string
str[i] = ' ';
str[len - 1]=' ';
}
// Driver code
public static void main(String args[])
{
String st="helloABworldABGfG";
char str[] = st.toCharArray();
translate(str);
System.out.println("The modified string is :");
System.out.println(str);
}
}
// This code is contributed
// by Nikita Tiwari.
Python3
# Python 3 program to replace all
# occurrences of "AB" with "C"
def translate(st) :
l = len(st)
if (l < 2) :
return
i = 0 # Index in modified string
j = 0 # Index in original string
# Traverse string
while (j < l - 1) :
# Replace occurrence of "AB" with "C"
if (st[j] == 'A' and st[j + 1] == 'B') :
# Increment j by 2
j += 2
st[i] = 'C'
i += 1
continue
st[i] = st[j]
i += 1
j += 1
if (j == l - 1) :
st[i] = st[j]
i += 1
# add a null character to
# terminate string
st[i] = ' '
st[l-1] = ' '
# Driver code
st = list("helloABworldABGfG")
translate(st)
print("The modified string is :")
print(''.join(st))
# This code is contributed by Nikita Tiwari.
C#
// Efficient C# program to replace
// all occurrences of "AB" with "C"
using System;
class GFG {
static void translate(char []str)
{
int len = str.Length;
if (len < 2)
return;
// Index in modified string
int i = 0;
// Index in original string
int j = 0;
// Traverse string
while (j < len - 1)
{
// Replace occurrence of "AB" with "C"
if (str[j] == 'A' && str[j + 1] == 'B')
{
// Increment j by 2
j = j + 2;
str[i++] = 'C';
continue;
}
str[i++] = str[j++];
}
if (j == len - 1)
str[i++] = str[j];
// add a null character to
// terminate string
str[i] = ' ';
str[len - 1]=' ';
}
// Driver code
public static void Main()
{
String st="helloABworldABGfG";
char []str = st.ToCharArray();
translate(str);
Console.Write("The modified string is :");
Console.Write(str);
}
}
// This code is contributed by nitin mittal.
JavaScript
<script>
// Efficient javascript program to replace
// all occurrences of "AB" with "C"
function translate(str)
{
var len = str.length;
if (len < 2)
return;
// Index in modified string
var i = 0;
// Index in original string
var j = 0;
// Traverse string
while (j < len - 1)
{
// Replace occurrence of "AB" with "C"
if (str[j] == 'A' && str[j + 1] == 'B')
{
// Increment j by 2
j = j + 2;
let firstPart = str.substr(0, i);
let lastPart = str.substr(i + 1);
str = firstPart + 'C' + lastPart;
i += 1;
continue;
}
let firstPart = str.substr(0, i);
let lastPart = str.substr(i + 1);
str = firstPart + str[j] + lastPart;
i += 1;
j += 1;
}
if (j == len - 1)
{
let firstPart = str.substr(0, i);
let lastPart = str.substr(i + 1);
str = firstPart + str[j] + lastPart;
i += 1;
}
// Add a null character to terminate string
let firstPart = str.substr(0, i);
let lastPart = str.substr(i + 1);
str = firstPart + ' ' + lastPart;
firstPart = str.substr(0, len - 1);
lastPart = str.substr(len);
str = firstPart + ' ' + lastPart;
// str[len - 1]=' ';
return str;
}
// Driver code
var str = "helloABworldABGfG";
document.write("The modified string is :" +
"<br>" + translate(str));
// This code is contributed by ipg2016107
</script>
OutputThe modified string is:
helloCworldCGfG
Time Complexity : O(n)
Auxiliary Space : O(1)
An Efficient solution to use only one index to modify/replace the string. If we find “AB” at current index, we increment i by 2 (i=i+2). Otherwise, we increment i by 1 (i=i+1).
Below is implementation:
Time Complexity : O(n)
Auxiliary Space : O(1)
The time complexity of this function is O(n) where n is the length of the input string ‘st’. This is because the function iterates through the string once, checking each pair of characters and potentially modifying the string in place.
The space complexity is O(1) because the function only uses a constant amount of extra space regardless of the size of the input string. The function modifies the input string in place without using any additional data structures that grow with the input size.
Similar Reads
Replace all occurrences of pi with 3.14 in a given string
Given a string, the task is to replace all occurrences of pi with 3.14 in the given string. Examples: Input : str = "2 * pi + 3 * pi = 5 * pi" Output : 2 * 3.14 + 3 * 3.14 = 5 * 3.14 Input : str = "pippppiiiipi" Output : 3.14ppp3.14iii3.14 Input : str = "xpix" Output : x3.14x Approach 1: Create an e
7 min read
Remove all occurrences of a character from a string using STL
Given a string S and a character C, the task is to remove all the occurrences of the character C from the given string. Examples: Input:vS = "GFG IS FUN", C = 'F' Output:GG IS UN Explanation: Removing all occurrences of the character 'F' modifies S to "GG IS UN". Therefore, the required output is GG
2 min read
Replace all occurrences of substring
Given three strings S, S1, and S2 consisting of N, M, and K characters respectively, the task is to modify the string S by replacing all the substrings S1 with the string S2 in the string S. Examples: Input: S = "abababa", S1 = "aba", S2 = "a"Output: abaExplanation: Change the substrings S[0, 2] and
10 min read
Remove all occurrences of string t in string s using KMP Algorithm
Given two strings s and t, the task is to remove all occurrences of t in s and return the modified string s, and you have to use the KMP algorithm to solve this. Examples: Input: s = "abcdefgabcabcabdefghabc", t = "abc"Output: "defgdefgh" Input: s = "aaabbbccc", t = "bbb"Output: "aaaccc" Approach: T
8 min read
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: babaExplanation:Replacing all
9 min read
Replace a character c1 with c2 and c2 with c1 in a string S
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : grrksfoegrrks, c1 = e, c2 = r Output : geeksforgeeks Input : ratul, c1 = t, c2 = h Output : rahul Traverse through the string and check for the occurrences of c1 and c2. If c1 is found then replace it with c2
5 min read
Encode given string by replacing substrings with prefix same as itself with *
Given string str of size N containing only lowercase English letters. The task is to encrypt the string such that the substrings having same prefix as itself are replaced by a *. Generate the encrypted string. Note: If the string can be encrypted in multiple ways, find the smallest encrypted string.
9 min read
Remove all occurrences of a word from a given string using Z-algorithm
Given two strings str of length N and word of length M, the task is to remove all the occurrences of the string word from the string str. Examples: Input: str = "asmGeeksasmasmForasmGeeks", word = "asm" Output: GeeksForGeeks Explanation: Removing "asm" from the string, str modifies str to GeeksForGe
15+ min read
Remove all occurrences of a string t in string s using Boyer-Moore Algorithm
Given a string s and string t, the task is to remove all occurrences of a string t in a string s using the Boyer-Moore algorithm. Examples: Input: s = "ababaababa", t = "aba" Output: baab Input: s = "Geeksforgeeks", t = "eek"Output: Gsforgs Approach: This can be solved with the following idea: We in
10 min read
Replace two substrings (of a string) with each other
Given 3 strings S, A and B. The task is to replace every sub-string of S equal to A with B and every sub-string of S equal to B with A. It is possible that two or more sub-strings matching A or B overlap. To avoid confusion about this situation, you should find the leftmost sub-string that matches A
7 min read