#2301
Match Substring After Replacement
HardArrayHash TableStringString MatchingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a sliding window technique combined with a mapping to quickly check if `sub` can be transformed into any substring of `s`. This reduces the number of comparisons and leverages the mappings effectively.
⚙️
Algorithm
3 steps- 1Step 1: Create a mapping dictionary from the mappings array for quick lookups.
- 2Step 2: Use a sliding window of size equal to `sub` to traverse `s`.
- 3Step 3: For each character in the current window, check if it matches the corresponding character in `sub` or can be transformed using the mapping.
solution.py15 lines
1def canMatchSubstring(s, sub, mappings):
2 mapping_dict = {}
3 for old, new in mappings:
4 mapping_dict.setdefault(old, []).append(new)
5 n, m = len(s), len(sub)
6 for i in range(n - m + 1):
7 if canTransform(sub, s[i:i + m], mapping_dict):
8 return True
9 return False
10
11def canTransform(sub, target, mapping_dict):
12 for i in range(len(sub)):
13 if sub[i] != target[i] and target[i] not in mapping_dict.get(sub[i], []):
14 return False
15 return Trueℹ
Complexity note: The time complexity is O(n) because we only traverse the string `s` once with a sliding window, and the space complexity is O(n) due to the mapping dictionary that stores possible transformations.
- 1Transformations can be represented as a mapping for quick lookups.
- 2Using a sliding window helps in efficiently checking substrings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.