VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-and-replace-all-occurrence-of-a-substring-in-the-given-string/

⇱ Replace all occurrences of substring - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Replace all occurrences of substring

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

[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.


Output
aba

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

The above approach can also be optimized by creating the longest proper 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:

  • Create a array lps[] that stores the longest proper prefix and suffix for each character and fill this array using the KMP algorithm for the string s1.
  • Initialize two variables say, i and j as 0 to store the position of current character in s and s1 respectively.
  • Initialize a array found[] to store all the starting indexes from which string s1 occurs in s.
  • Iterate over the characters of the string s using variable i and perform the following steps:
    • If s[i] is equal to s1[j], then increment i and j by 1.
    • If j is equal to the length of s1, then add the value (i - j) to the array found and update j as lps[j - 1].
    • Otherwise, if the value of s[i] is not equal to s1[j], then if j is equal to 0, then increment the value of i by 1. Otherwise, update j as lps[j - 1].
  • Initialize a variable say, prev as 0 to store the last changed index and an empty string ans to store the resultant string after replacing all the initial appearances of s1 by s2 in s.
  • Traverse the array found[] and if the value of found[i] is greater than prev, then add the string s2 in place of s1 in ans.
  • After completing the above steps, print the string ans as the result.

Output
aba

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


Output
aba
Comment
Article Tags: