DIY: Find and Replace in a String
Solve the interview question "Find and Replace in a String" in this lesson.
We'll cover the following
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 theindices[i]
position. The make the replacement, we have to replacesources[i]
withtargets[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.
Input
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"]
Output
The output of the function will be the string obtained after the replacements. The following is the output for the above-mentioned inputs:
"vbfrssozp"
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.