Find And Replace in String - Problem
You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k.
To complete the ith replacement operation:
- Check if the substring
sources[i]occurs at indexindices[i]in the original strings. - If it does not occur, do nothing.
- Otherwise if it does occur, replace that substring with
targets[i].
For example, if s = "abcd", indices[i] = 0, sources[i] = "ab", and targets[i] = "eee", then the result of this replacement will be "eeecd".
All replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap.
Return the resulting string after performing all replacement operations on s.
Input & Output
Example 1 — Basic Replacement
$
Input:
s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"]
›
Output:
"eeebffff"
💡 Note:
At index 0, "a" matches source "a", replace with "eee". At index 2, "cd" matches source "cd", replace with "ffff".
Example 2 — No Match
$
Input:
s = "abcd", indices = [0, 2], sources = ["ab", "ec"], targets = ["eee", "ffff"]
›
Output:
"eeecd"
💡 Note:
At index 0, "ab" matches, replace with "eee". At index 2, "cd" ≠ "ec", no replacement.
Example 3 — Multiple Operations
$
Input:
s = "vmokgggqzp", indices = [3, 5, 1], sources = ["kg", "ggq", "mo"], targets = ["s", "so", "bfr"]
›
Output:
"vbfrssozp"
💡 Note:
Replace "mo" at index 1 with "bfr", "kg" at index 3 with "s", and "ggq" at index 5 with "so".
Constraints
- 1 ≤ s.length ≤ 1000
- k == indices.length == sources.length == targets.length
- 1 ≤ k ≤ 100
- 0 ≤ indices[i] < s.length
- 1 ≤ sources[i].length, targets[i].length ≤ 50
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with replacement specifications
2
Validate
Check which replacements are valid
3
Apply
Perform all valid replacements simultaneously
Key Takeaway
🎯 Key Insight: Sort replacements by index descending to avoid position shifts during simultaneous replacements
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code