Find And Replace in String

Apply several find-and-replace operations to a string at once, each checked against the original string.

Given a string s and k replacement operations, return the string after all of them are applied. The operations come as three arrays of length k: indices, sources and targets. Operation i checks whether sources[i] appears in s starting at position indices[i]. If it does, that part is replaced with targets[i]; if not, the operation does nothing.

All operations are checked against the original s and applied at the same time, and the parts they replace never overlap.

Example 1
Input: s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"]
Output: "eeebffff"
Example 2
Input: s = "abcd", indices = [0, 2], sources = ["ab", "ec"], targets = ["eee", "ffff"]
Output: "eeecd"
Explanation: "ec" does not appear at position 2, so that operation does nothing.
Solution

The Idea

You have probably used find and replace in a text editor: you type a word, type what should go in its place, and the editor swaps them. Here there are several replacements at once, and each one names the exact position where its word must start.

In Example 1, s is "abcd". Operation 0 says: if "a" starts at position 0, put "eee" there. Operation 1 says: if "cd" starts at position 2, put "ffff" there. Both words are where the operations expect them, so the answer is "eee", then the untouched "b", then "ffff": "eeebffff".

The obvious plan is to apply operation 0 to the string, then operation 1 to what comes out. Does that work? Look at the picture below.

The original string abcd, with operation 0 replacing a by eee and operation 1 replacing cd by ffff. In the row one by one, after operation 0 the string is eeebcd and position 2 holds e, so cd is not found. In the row built from the original, the result is eeebffff.

In the row labelled "one by one", operation 0 has already turned "a" into "eee". The string is now "eeebcd", two characters longer, and everything after the replacement has moved two places to the right. Position 2 now holds an e, so operation 1 no longer finds "cd", and the result stays "eeebcd", which is wrong.

The positions in indices describe the original string, so every check has to read the original. The answer is then a new string, written from left to right. Where an operation matched, write its target and jump over its source; everywhere else, copy the character. The row labelled "built from the original" shows this: e, e, e from operation 0, the b copied, then f, f, f, f from operation 1.

Solution Approach

Turning that idea into code means settling three things: which operations match, which operation starts at each position, and how the new string is built. Replacing from right to left, an alternative order, comes last.

Checking which operations match

How do we check one operation against the original? s.startsWith(sources[i], indices[i]) answers exactly that. It is true when the characters of s from position indices[i] on begin with sources[i]. It is also false when the source would run past the end of s, so no separate length check is needed. Since s itself never changes, every check reads the original.

Finding the operation at each position

The operations do not have to come in order of position: Example 1 could just as well list the "cd" operation first. So how does a left-to-right walk know which operation, if any, starts where it stands?

Keep an array op with one entry per position of s. op[p] holds the number of the operation that matched at position p, or -1 when none did. An empty entry is marked with -1 because 0 is a real operation number. For Example 1, op is [0, -1, 1, -1]. Filling it takes one pass over the operations, and after that each lookup is a single read.

Building the new string

What does the walk do at each position? A StringBuilder, Java's growable buffer of characters, collects the result, and a marker i starts at 0. If op[i] names an operation, its target is appended and i jumps forward by the length of its source, past the replaced characters. Otherwise the character at i is copied and i moves one step. The replaced parts never overlap, so a jump never skips the start of another match.

Replacing from right to left (optional)

Is there a way to keep the one-by-one plan? Yes, if the order changes: sort the operations by position, largest first, and replace starting from the right end. A replacement only moves the characters after it, and every operation still to come sits further left, so its position is still correct. It needs a sort, though, and each replacement on a Java String makes a new copy of the whole string. The single left-to-right build does less work.

Java Solution

The method findReplaceString works in these steps:

  1. First, create the array op, one entry per character of s, and set every entry to -1 with Arrays.fill(op, -1).
  2. Loop over the operations with k. When s.startsWith(sources[k], indices[k]) is true, store k in op[indices[k]].
  3. Create a StringBuilder named sb for the result, and start the marker i at 0.
  4. While i is inside s, look at op[i]. If it holds an operation, append targets[op[i]] to sb and add the length of sources[op[i]] to i. Otherwise append s.charAt(i) and move i one step.
  5. When i reaches the end of s, return sb.toString().

The main method runs both examples, Example 1 with its operations listed in the opposite order, a source that would run past the end of the string, and two operations with empty targets.

Java
import java.util.Arrays;

public class FindAndReplaceInString {

    public static String findReplaceString(String s, int[] indices, String[] sources,
                                           String[] targets) {
        int[] op = new int[s.length()];       // op[p]: which operation replaces at p, or -1
        Arrays.fill(op, -1);
        for (int k = 0; k < indices.length; k++) {
            if (s.startsWith(sources[k], indices[k])) {
                op[indices[k]] = k;           // checked against the ORIGINAL string
            }
        }
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < s.length()) {
            if (op[i] >= 0) {
                sb.append(targets[op[i]]);
                i += sources[op[i]].length(); // skip the replaced part
            } else {
                sb.append(s.charAt(i++));
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(findReplaceString("abcd", new int[] {0, 2},
                new String[] {"a", "cd"}, new String[] {"eee", "ffff"}));
        System.out.println(findReplaceString("abcd", new int[] {0, 2},
                new String[] {"ab", "ec"}, new String[] {"eee", "ffff"}));
        System.out.println(findReplaceString("abcd", new int[] {2, 0},
                new String[] {"cd", "a"}, new String[] {"ffff", "eee"}));
        System.out.println(findReplaceString("abc", new int[] {2},
                new String[] {"cde"}, new String[] {"x"}));
        System.out.println(findReplaceString("a-b-c", new int[] {3, 1},
                new String[] {"-", "-"}, new String[] {"", ""}));
    }
}

Running it prints:

Output
eeebffff
eeecd
eeebffff
abc
abc

The first line, eeebffff, is Example 1 with both operations applied. In eeecd, Example 2, "ab" became "eee", while "ec" was not found at position 2, so "cd" stayed as it was.

Look at the third line: eeebffff again, although this time the "cd" operation came first. op is indexed by position, so the order of the operations makes no difference.

The fourth line is "abc", unchanged. "cde" would need positions 2 to 4, but "abc" has only three characters, and startsWith simply returns false instead of throwing an exception. The last line is also "abc", this time made from "a-b-c": both dashes were replaced by empty strings, so a target can delete text too.

Complexity

The work is one check per operation, plus one walk over s that copies characters and targets. Let n be the length of s and L the total length of all sources and targets.

  • Time: O(n + L), because filling op touches each of the n positions once, each startsWith compares at most the characters of one source, and the walk appends each kept character and each used target once.
  • Space: O(n) besides the result, for the op array with its one entry per position of s. The StringBuilder holds the result itself, whose length depends on the targets.

Building a string piece by piece with a StringBuilder also comes up in Encode and Decode Strings.