KatInterview

862. Find And Replace in String

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core challenge of this problem is to perform multiple substring replacement operations on a string. The key constraints are that all operations must be considered "simultaneously" and that the replacement regions will not overlap. "Simultaneously" means that the decision to perform a replacement at a certain index must be based on the original string s, not on a string that has already been partially modified by other replacements. The non-overlapping guarantee simplifies the problem by removing the need to resolve conflicting replacements at the same or nearby positions.

Solution

Find And Replace in String in Python

class Solution:
    def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
        # Map start index to the corresponding operation index
        replacements = {}
        for i, idx in enumerate(indices):
            # Check if the source string matches the substring in s at the given index.
            if s.startswith(sources[i], idx):
                replacements[idx] = i

        # Use a list to build the parts of the new string efficiently.
        result_parts = []
        i = 0
        n = len(s)
        while i < n:
            if i in replacements:
                # If a replacement starts at index i...
                op_idx = replacements[i]
                # Append the target string.
                result_parts.append(targets[op_idx])
                # Advance the pointer past the source string.
                i += len(sources[op_idx])
            else:
                # No replacement, append the original character.
                result_parts.append(s[i])
                i += 1
        
        # Join the parts to form the final string.
        return "".join(result_parts)

Find And Replace in String in Java

class Solution {
    public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
        int n = s.length();
        int k = indices.length;
        
        // Use a map to store the valid replacements.
        // Key: start index in s, Value: index of the operation in the input arrays.
        Map<Integer, Integer> replacements = new HashMap<>();
        for (int i = 0; i < k; i++) {
            // Check if the source string is a prefix of s at the given index.
            if (s.startsWith(sources[i], indices[i])) {
                replacements.put(indices[i], i);
            }
        }
        
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < n) {
            if (replacements.containsKey(i)) {
                // If a replacement should happen at this index...
                int op_idx = replacements.get(i);
                // Append the target string.
                sb.append(targets[op_idx]);
                // Advance the pointer by the length of the source string.
                i += sources[op_idx].length();
            } else {
                // Otherwise, append the original character.
                sb.append(s.charAt(i));
                i++;
            }
        }
        
        return sb.toString();
    }
}

Find And Replace in String in C++

class Solution {
public:
    string findReplaceString(string s, vector<int>& indices, vector<string>& sources, vector<string>& targets) {
        int n = s.length();
        int k = indices.size();
        
        // This map stores which operation (from 0 to k-1) matches at which index in s.
        // Key: start index in s, Value: index of the operation in the input arrays.
        unordered_map<int, int> replacements;
        for (int i = 0; i < k; ++i) {
            int idx = indices[i];
            // Check if the substring of s starting at idx matches sources[i].
            if (s.substr(idx, sources[i].length()) == sources[i]) {
                replacements[idx] = i;
            }
        }
        
        string result;
        // Pre-allocating memory can be a minor optimization.
        result.reserve(n);
        
        int i = 0;
        while (i < n) {
            // Check if a replacement should happen at this index.
            if (replacements.count(i)) {
                int op_idx = replacements[i];
                // Append the target string.
                result.append(targets[op_idx]);
                // And jump the pointer i past the source string.
                i += sources[op_idx].length();
            } else {
                // No replacement, append the original character.
                result.push_back(s[i]);
                i++;
            }
        }
        
        return result;
    }
};

Find And Replace in String in TypeScript

function findReplaceString(s: string, indices: number[], sources: string[], targets: string[]): string {
    const n = s.length;
    const k = indices.length;

    // Use a map to store valid replacements.
    // Key: start index in s, Value: the index of the operation.
    const replacements = new Map<number, number>();
    for (let i = 0; i < k; i++) {
        const idx = indices[i];
        const source = sources[i];
        // Check if the source string matches the substring in s at the given index.
        if (s.startsWith(source, idx)) {
            replacements.set(idx, i);
        }
    }

    const resultParts: string[] = [];
    let i = 0;
    while (i < n) {
        if (replacements.has(i)) {
            // If a replacement should happen at this index...
            const op_idx = replacements.get(i)!;
            // Append the target string.
            resultParts.push(targets[op_idx]);
            // Advance the pointer by the length of the source string.
            i += sources[op_idx].length;
        } else {
            // Otherwise, append the original character.
            resultParts.push(s[i]);
            i++;
        }
    }

    return resultParts.join('');
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.