Problem Description
Given two strings, str1 and str2, we need to construct a string word of length (n + m - 1) such that for every index i (0 <= i < n) the substring of length m starting at index i in word meets a constraint:
- If str1[i] == 'T', then word[i...i+m-1] must be exactly equal to str2.
- If str1[i] == 'F', then word[i...i+m-1] must not equal str2. Return the lexicographically smallest word that satisfies all these constraints; if none exists, return an empty string.
Key Insights
- The output word has fixed length: n + m - 1.
- 'T' constraints completely fix the substring at a given starting index to be equal to str2.
- 'F' constraints require deviation from str2 in the corresponding substring.
- Overlapping substrings impose consistency requirements.
- A greedy approach is used: start with the smallest possible characters (i.e., 'a') and override them where constraints force a different letter.
- For any 'F' constraint where the current assignment accidentally equals str2, we try to minimally modify one character in order to break the match without violating other constraints.
Space and Time Complexity
Time Complexity: O(n * m) in the worst case, due to scanning and possibly adjusting m characters for each of the n positions. Space Complexity: O(n + m) for storing the final word and auxiliary variables.
Solution
We approach the problem in two phases:
- Initialize the word with all 'a' (the lexicographically smallest letter). For every index i where str1[i]=='T', force the substring word[i...i+m-1] to equal str2, checking for consistency in overlapping positions.
- For each index i with str1[i]=='F', verify if the substring equals str2. If it does, modify one character minimally (by choosing the next possible letter) so that the substring no longer equals str2. If no valid adjustment is possible, return an empty string. This greedy strategy, along with careful handling of overlaps, yields the lexicographically smallest possible valid word.