HardNo. 2301

Match Substring After Replacement — LeetCode 2301 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, String, String Matching
Reading time
2 min

The problem

You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: Replace a character oldi of sub with newi.

Example

Input
s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]]
Output
true
Explanation
Replace the first 'e' in sub with '3' and 't' in sub with '7'.

Python solution

PythonSolution
class Solution:
    def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:
        d = defaultdict(set)
        for a, b in mappings:
            d[a].add(b)
        for i in range(len(s) - len(sub) + 1):
            if all(a == b or a in d[b] for a, b in zip(s[i : i + len(sub)], sub)):
                return True
        return False

Complexity

Time
O(m × n)
Space · auxiliary
O(C2)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2301. Match Substring After Replacement is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2306Naming a CompanyHard
0049Group AnagramsMedium
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard
0500Keyboard RowEasy

Frequently asked questions

How hard is LeetCode 2301. Match Substring After Replacement?

LeetCode 2301. Match Substring After Replacement is rated Hard on LeetCode.

What is the time complexity of LeetCode 2301. Match Substring After Replacement?

The Python solution on this page runs in O(m × n).

What is the space complexity of LeetCode 2301. Match Substring After Replacement?

The Python solution on this page uses O(C2) auxiliary space.

What topics does LeetCode 2301. Match Substring After Replacement cover?

LeetCode 2301. Match Substring After Replacement is tagged Array, Hash Table, String and String Matching 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.