LeetCode solutions

2393. Match Substring After Replacement

My accepted Python solution to LeetCode problem 2393, Match Substring After Replacement, running in 2351ms.

  • Difficulty: Hard
  • Python
  • Runtime 2351ms
  • Memory 17.9MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 2351ms, memory 17.9MB, accepted 2026-01-02.

python
class Solution:
    def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:
        # Build mapping dict: for each char in sub, what chars can it become
        allowed = {}
        for old, new in mappings:
            if old not in allowed:
                allowed[old] = set([old])
            allowed[old].add(new)
        
        n, m = len(s), len(sub)
        for i in range(n - m + 1):
            match = True
            for j in range(m):
                if sub[j] == s[i + j]:
                    continue
                if sub[j] in allowed and s[i + j] in allowed[sub[j]]:
                    continue
                match = False
                break
            if match:
                return True
        return False

Source