Problem Description
You are given two strings, str1
and str2
, of lengths n
and m
, respectively. A string word
of length n + m - 1
is defined to be generated by str1
and str2
if it satisfies specific conditions based on the characters in str1
. Return the lexicographically smallest possible string that can be generated by str1
and str2
. If no string can be generated, return an empty string.
Key Insights
- The character 'T' in
str1
indicates that the substring starting from that index must matchstr2
. - The character 'F' in
str1
indicates that the substring starting from that index must not matchstr2
. - The solution requires careful construction of the string while ensuring it remains lexicographically smallest.
- A greedy approach can be implemented to select the smallest possible characters at each index while respecting the conditions imposed by
str1
.
Space and Time Complexity
Time Complexity: O(n * m)
Space Complexity: O(n + m)
Solution
To solve this problem, we will use a greedy approach combined with string manipulation. The idea is to iterate through str1
and build the resulting string word
. We will maintain a character array to hold the current state of the generated string. For each index in str1
, depending on whether it is 'T' or 'F', we will either match str2
or avoid it by selecting the smallest possible character that does not lead to an invalid configuration.
- Create an array
result
of sizen + m - 1
initialized with placeholder characters. - Iterate through
str1
:- For 'T', place
str2
starting at the current index. - For 'F', ensure that the substring does not match
str2
.
- For 'T', place
- If at any point the conditions cannot be satisfied, return an empty string.
- Construct the final result string from the
result
array.