In the Find And Replace in String coding problem, you are given a base string s and several replacement operations. Each operation consists of an index, a source string, and a target string. An operation is only performed if the substring of s starting at index exactly matches source. Crucially, all replacements must be determined based on the original string, and they must not interfere with each other.
Google uses this to test your ability to handle overlapping string modifications and sorting. Since replacing a string with a longer or shorter target changes the indices of subsequent characters, doing it "on the fly" is prone to errors. It evaluation your proficiency with Hash Tables and the String interview pattern of building a result string incrementally while mapping original positions to new values.
The problem is best solved by Preprocessing and Building.
s.startsWith(source, index).s using a pointer i = 0.i has a valid replacement:
target string to your result.i by the length of the source string.i:
s[i] to the result.i by 1.s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"]
indices array in the input invalid for subsequent operations.When performing multiple modifications on a string, don't try to edit the string in place. Instead, treat the original string as a read-only template and use a StringBuilder or a list of characters to construct the final output. This avoids complex index arithmetic.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Group Anagrams | Medium | Solve | |
| Alert Using Same Key-Card Three or More Times in a One Hour Period | Medium | Solve | |
| Before and After Puzzle | Medium | Solve | |
| Groups of Special-Equivalent Strings | Medium | Solve | |
| High-Access Employees | Medium | Solve |