MediumNo. 0833

Find And Replace in String — LeetCode 833 Python Solution

Pattern
Sorting
Topics
Array, Hash Table, String, Sorting
Reading time
4 min

The 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.

Example

Input
s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"]
Output
"eeebffff"
Explanation
"a" occurs at index 0 in s, so we replace it with "eee".

Python solution

PythonSolution
class Solution:
    def findReplaceString(
        self, s: str, indices: List[int], sources: List[str], targets: List[str]
    ) -> str:
        n = len(s)
        d = [-1] * n
        for k, (i, src) in enumerate(zip(indices, sources)):
            if s.startswith(src, i):
                d[i] = k
        ans = []
        i = 0
        while i < n:
            if ~d[i]:
                ans.append(targets[d[i]])
                i += len(sources[d[i]])
            else:
                ans.append(s[i])
                i += 1
        return "".join(ans)

Complexity

Time
O(L)
Space · auxiliary
O(n)where L is the sum of the lengths of all strings, and n is the length of the string s

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 833. Find And Replace in String is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0049Group AnagramsMedium
0522Longest Uncommon Subsequence IIMedium
0692Top K Frequent WordsMedium
0720Longest Word in DictionaryMedium
0721Accounts MergeMedium
0792Number of Matching SubsequencesMedium

Frequently asked questions

How hard is LeetCode 833. Find And Replace in String?

LeetCode 833. Find And Replace in String is rated Medium on LeetCode.

What is the time complexity of LeetCode 833. Find And Replace in String?

The Python solution on this page runs in O(L).

What is the space complexity of LeetCode 833. Find And Replace in String?

The Python solution on this page uses O(n), where L is the sum of the lengths of all strings, and n is the length of the string s auxiliary space.

What topics does LeetCode 833. Find And Replace in String cover?

LeetCode 833. Find And Replace in String is tagged Array, Hash Table, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.