DIY: Find and Replace in a String

Solve the interview question "Find and Replace in a String" in this lesson.

Problem statement

For this challenge, you will be given a string, s. Your task will be to perform replacement operations in this string that replace substrings with new ones and return the resultant string. For the replacements, you will be given a list of indices, a list of strings called sources, and a list of strings called targets.

The replacement should only take place if the sources[i] substring starts at the indices[i] position. The make the replacement, we have to replace sources[i] with targets[i] in the original string.

Note that the sources[i] and targets[i] substrings can have different lengths. Therefore, the resultant string can differ in length from the original string.


The function will take four arguments: a string called s, an array of integers called indices, an array of strings called sources, and another array of strings called targets. Let’s consider the following inputs:

s = "vmokgggqzp"
indices = [3,5,1]
sources = ["kg","ggq","mo"]
targets = ["s","so","bfr"]


The output of the function will be the string obtained after the replacements. The following is the output for the above-mentioned inputs:


Level up your interview prep. Join Educative to access 70+ hands-on prep courses.