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
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read