Problem Description
Given two strings s and sub along with a list of mappings that allow you to replace a character in sub with a new character (each character in sub can be replaced at most once), determine if it is possible to transform sub (using zero or more allowed replacements) into a substring of s.
Key Insights
- For each character in sub, create a set of possible characters it can become (including itself).
- The mapping operation is one-time per character index in sub—once replaced, no further changes are allowed for that character.
- Use a sliding window in s of length equal to sub and for each candidate window, verify that each character in the window is allowed by the corresponding character’s replacement set.
- Precompute the allowed replacements for all characters in sub to optimize the per-window checking.
Space and Time Complexity
Time Complexity: O(n * L) where n = len(s) and L = len(sub). In the worst case, this is acceptable given the constraints. Space Complexity: O(L + M) where L is the length of sub (for storing allowed sets for each character) and M is the number of mappings.
Solution
We first build a mapping dictionary that, for every character in sub, contains a set of possible characters it can be (including itself and any allowed replacements). Then, we slide a window of the same length as sub through s. For every window, we compare each character with the allowed set corresponding to the position in sub. If all characters in the window match the allowed possibilities, we return true. If no matching window is found after checking all possible positions, we return false.