Problem Description
Given a 0-indexed string s and three 0-indexed arrays indices, sources, and targets of equal length, perform k replacement operations on s. For each operation, check if the substring sources[i] exactly appears in s starting at indices[i]. If it does, replace that substring with targets[i]. All replacements occur simultaneously (i.e., they do not affect each other’s indexing). The replacements are guaranteed not to overlap.
Key Insights
- Use a mapping (or dictionary) from index to its respective source and target strings.
- Process the string in one pass, checking at each index if a replacement should occur.
- To ensure the original string’s indexing does not get invalidated, either use a pointer scan with conditional skipping or sort replacements in descending order.
- The problem guarantees non-overlapping replacements.
Space and Time Complexity
Time Complexity: O(n + k * m), where n is the length of s and m is the average length of source strings. Space Complexity: O(n) for the output string (and O(k) additional space for the mapping).
Solution
The solution uses a dictionary (or mapping) to record the indices and corresponding (source, target) pairs. Then iterate through the string with a pointer. At each position, check if there is a replacement defined (i.e., the current index is a key in the mapping). If so, verify that s starting at that index matches the source string. If it matches, append the target string to the result and skip ahead by the length of the source. Otherwise, simply append the current character to the result. This guarantees simultaneous replacements without affecting the indexing for subsequent operations.