Replace all occurrences of substring (original) (raw)

Last Updated : 23 Jul, 2025

Given three strings **s, **s1, and **s2 of lengths **n, **m, and **k 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: aba
**Explanation: Change the substrings s[0, 2] and s[4, 6] to the string s2 modifies the string s to "aba".

**Input: s ="geeksforgeeks", s1 = "eek", s2 = "ok"
**Output: goksforgoks
**Explanation: Change the substrings s[1, 3] and s[9, 11] to the string

Table of Content

[Naive Approach] Using Nested Loop– O(n*m) Time and O(n) Space

The simplest approach to solve the given problem is to traverse the string **s and when any string **s1 is found as a substring in the string **s then replace it by **s2.

C++ `

#include #include using namespace std;

string replaceSubstr(string s, string s1, string s2) { string ans = ""; int n = s.length(), m = s1.length();

for (int i = 0; i < n; i++)
{
    if (i + m <= n && s.substr(i, m) == s1)
    {
        ans += s2;

        // Skip the characters of s1
        i += m - 1;
    }
    else
    {
        ans += s[i];
    }
}
return ans;

}

int main() { string s = "abababa", s1 = "aba", s2 = "a"; cout << replaceSubstr(s, s1, s2) << endl; return 0; }

Java

public class GFG { public static String replaceSubstr(String s, String s1, String s2) { StringBuilder ans = new StringBuilder(); int n = s.length(), m = s1.length();

    for (int i = 0; i < n; i++) {
        if (i + m <= n
            && s.substring(i, i + m).equals(s1)) {
            ans.append(s2);

            // Skip the characters of s1
            i += m - 1;
        }
        else {
            ans.append(s.charAt(i));
        }
    }
    return ans.toString();
}

public static void main(String[] args)
{
    String s = "abababa", s1 = "aba", s2 = "a";
    System.out.println(replaceSubstr(s, s1, s2));
}

}

Python

def replaceSubstr(s, s1, s2): ans = "" n, m = len(s), len(s1)

i = 0
while i < n:
    if i + m <= n and s[i:i + m] == s1:
        ans += s2

        # Skip the characters of s1
        i += m - 1
    else:
        ans += s[i]
    i += 1
return ans

s = "abababa" s1 = "aba" s2 = "a" print(replaceSubstr(s, s1, s2))

C#

using System;

class GFG { static string ReplaceSubstr(string s, string s1, string s2) { string ans = ""; int n = s.Length, m = s1.Length;

    for (int i = 0; i < n; i++) {
        if (i + m <= n && s.Substring(i, m) == s1) {
            ans += s2;

            // Skip the characters of s1
            i += m - 1;
        }
        else {
            ans += s[i];
        }
    }
    return ans;
}

static void Main()
{
    string s = "abababa", s1 = "aba", s2 = "a";
    Console.WriteLine(ReplaceSubstr(s, s1, s2));
}

}

JavaScript

function replaceSubstr(s, s1, s2) { let ans = ""; let n = s.length, m = s1.length;

for (let i = 0; i < n; i++) {
    if (i + m <= n && s.substring(i, i + m) === s1) {
        ans += s2;

        // Skip the characters of s1
        i += m - 1;
    }
    else {
        ans += s[i];
    }
}
return ans;

}

let s = "abababa"; let s1 = "aba"; let s2 = "a"; console.log(replaceSubstr(s, s1, s2));

`

[Expected Approach] Using KMP Algorithm– O(n+m) Time and O(m) Space

The above approach can also be optimized by creating the longestproper prefix and suffix array for the string s1 and then perform the KMP Algorithm to find the occurrences of the string s1 in the string **s.

Algorithm:

#include #include using namespace std;

// Compute the LPS (Longest Prefix Suffix) array vector computeLPS(string pattern) { int m = pattern.length(); vector lps(m, 0); int len = 0;

for (int i = 1; i < m; ) {
    if (pattern[i] == pattern[len]) {
        lps[i++] = ++len;
    } else {
        if (len != 0) len = lps[len - 1];
        else lps[i++] = 0;
    }
}

return lps;

}

// Function to perform the replace using KMP string replaceSubstr(string s, string s1, string s2) { int n = s.length(); int m = s1.length(); vector lps = computeLPS(s1);

string ans;
int i = 0, j = 0;

while (i < n) {
    if (s[i] == s1[j]) {
        i++, j++;
        if (j == m) {
            // Match found; replace
            ans += s2;
            j = 0;  // Reset pattern pointer for next match
        }
    } else {
        if (j != 0) j = lps[j - 1];
        else {
            ans += s[i++];
        }
    }
}

// Add remaining unmatched characters
if (j != 0) ans += s.substr(i - j, j);

return ans;

}

int main() { string s = "abababa", s1 = "aba", s2 = "a"; cout << replaceSubstr(s, s1, s2) << endl; return 0; }

Java

import java.util.*;

public class GfG{

// Compute the LPS (Longest Prefix Suffix) array
public static int[] computeLPS(String pattern) {
    int m = pattern.length();
    int[] lps = new int[m];
    int len = 0;

    for (int i = 1; i < m; ) {
        if (pattern.charAt(i) == pattern.charAt(len)) {
            lps[i++] = ++len;
        } else {
            if (len != 0) len = lps[len - 1];
            else lps[i++] = 0;
        }
    }

    return lps;
}

// Function to perform the replace using KMP
public static String replaceSubstr(String s, String s1, String s2) {
    int[] lps = computeLPS(s1);
    StringBuilder ans = new StringBuilder();
    int i = 0, j = 0;
    int n = s.length(), m = s1.length();

    while (i < n) {
        if (s.charAt(i) == s1.charAt(j)) {
            i++; j++;
            if (j == m) {
                // Match found; replace
                ans.append(s2);
                j = 0;  // Reset pattern pointer for next match
            }
        } else {
            if (j != 0) j = lps[j - 1];
            else ans.append(s.charAt(i++));
        }
    }

    // Add remaining unmatched characters
    if (j != 0) ans.append(s.substring(i - j, i));

    return ans.toString();
}

public static void main(String[] args) {
    String s = "abababa", s1 = "aba", s2 = "a";
    System.out.println(replaceSubstr(s, s1, s2));
}

}

Python

Compute the LPS (Longest Prefix Suffix) array

def compute_lps(pattern): m = len(pattern) lps = [0] * m length = 0 i = 1 while i < m: if pattern[i] == pattern[length]: length += 1 lps[i] = length i += 1 else: if length != 0: length = lps[length - 1] else: lps[i] = 0 i += 1 return lps

Function to perform the replace using KMP

def replaceSubstr(s, s1, s2): n, m = len(s), len(s1) lps = compute_lps(s1) ans = [] i = j = 0

while i < n:
    if s[i] == s1[j]:
        i += 1
        j += 1
        if j == m:
            
            # Match found; replace
            ans.append(s2)
            
            # Reset pattern pointer for next match
            j = 0  
    else:
        if j != 0:
            j = lps[j - 1]
        else:
            ans.append(s[i])
            i += 1

# Add remaining unmatched characters
if j != 0:
    ans.append(s[i - j:i])

return ''.join(ans)

if name == 'main': s = "abababa" s1 = "aba" s2 = "a"; print(replaceSubstr(s, s1, s2))

C#

using System; using System.Text;

class GfG{

// Compute the LPS (Longest Prefix Suffix) array
static int[] ComputeLPS(string pattern) {
    int m = pattern.Length;
    int[] lps = new int[m];
    int len = 0;
    int i = 1;

    while (i < m) {
        if (pattern[i] == pattern[len]) {
            lps[i++] = ++len;
        } else {
            if (len != 0) len = lps[len - 1];
            else lps[i++] = 0;
        }
    }

    return lps;
}

// Function to perform the replace using KMP
static string replaceSubstr(string s, string s1, string s2) {
    int[] lps = ComputeLPS(s1);
    StringBuilder ans = new StringBuilder();
    int i = 0, j = 0;
    int n = s.Length, m = s1.Length;

    while (i < n) {
        if (s[i] == s1[j]) {
            i++; j++;
            if (j == m) {
                // Match found; replace
                ans.Append(s2);
                j = 0;  // Reset pattern pointer for next match
            }
        } else {
            if (j != 0) j = lps[j - 1];
            else ans.Append(s[i++]);
        }
    }

    // Add remaining unmatched characters
    if (j != 0) ans.Append(s.Substring(i - j, j));

    return ans.ToString();
}

static void Main() {
    string s = "abababa", s1 = "aba", s2 = "a";
    Console.WriteLine(replaceSubstr(s, s1, s2));
}

}

JavaScript

// Compute the LPS (Longest Prefix Suffix) array function computeLPS(pattern) { const m = pattern.length; const lps = Array(m).fill(0); let len = 0;

for (let i = 1; i < m;) {
    if (pattern[i] === pattern[len]) {
        lps[i++] = ++len;
    } else {
        if (len !== 0) len = lps[len - 1];
        else lps[i++] = 0;
    }
}
return lps;

}

// Function to perform the replace using KMP function replaceSubstr(s, s1, s2) { const lps = computeLPS(s1); let ans = ""; let i = 0, j = 0; const n = s.length, m = s1.length;

while (i < n) {
    if (s[i] === s1[j]) {
        i++; j++;
        if (j === m) {
            // Match found; replace
            ans += s2;
            j = 0;  // Reset pattern pointer for next match
        }
    } else {
        if (j !== 0) j = lps[j - 1];
        else ans += s[i++];
    }
}

// Add remaining unmatched characters
if (j !== 0) ans += s.slice(i - j, i);
return ans;

}

// Driver Code const s = "abababa", s1 = "aba", s2 = "a"; console.log(replaceSubstr(s, s1, s2));

`

****Time Complexity:**The time complexity is O(n + m), where n is the length of string s and m is the length of string s1.
The LPS function runs in **O(m) time to compute the prefix-suffix array, and the main loop processes string s in **O(n) time.
****Auxiliary Space:**The LPS array requires **O(m) space, where m is the length of s1, so the overall space complexity is **O(m).

Using Library Methods - O(n*m) time and O(n) space

C++ `

#include #include using namespace std;

// Function to perform the replace string replaceSubstr(string s, const string& s1, const string& s2) { size_t pos = 0;

// Replace all non-overlapping occurrences of s1 with s2
while ((pos = s.find(s1, pos)) != string::npos) {
    s.replace(pos, s1.length(), s2);
    
    // Move past the replaced part
    pos += s2.length();  
}

return s;

}

int main() { string s = "abababa", s1 = "aba", s2 = "a"; cout << replaceSubstr(s, s1, s2) << endl; return 0; }

Java

public class GfG {

// Function to perform the replace
static String replaceSubstr(String s, String s1,
                                String s2) {
    
    // Replace all non-overlapping occurrences
    return s.replace(s1, s2);
}

public static void main(String[] args) {
    String s = "abababa", s1 = "aba", s2 = "a";
    System.out.println(replaceSubstr(s, s1, s2));
}

}

Python

Function to perform the replace

def replaceSubstr(s, s1, s2):

# Replace all non-overlapping occurrences
return s.replace(s1, s2)

if name == "main": s = "abababa" s1 = "aba" s2 = "a" print(replaceSubstr(s, s1, s2))

C#

using System;

class GfG{

// Function to perform the replace 
static string replaceSubstr(string s, string s1, string s2) {
    
    // Replace all non-overlapping occurrences
    return s.Replace(s1, s2);
}

static void Main() {
    string s = "abababa", s1 = "aba", s2 = "a";
    Console.WriteLine(replaceSubstr(s, s1, s2));
}

}

JavaScript

// Function to perform the replace function replaceSubstr(s, s1, s2) {

// Replace all non-overlapping occurrences
return s.replaceAll(s1, s2);  // ES2021+

// Or for older environments:
// return s.split(s1).join(s2);

}

// Driver Code const s = "abababa", s1 = "aba", s2 = "a"; console.log(replaceSubstr(s, s1, s2));

`