Lexicographically Smallest Generated String Problem
#3474
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3474.
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 the following conditions for each index 0 <= i <= n - 1:
- If
str1[i] == 'T', the substring ofwordwith sizemstarting at indexiis equal tostr2, i.e.,word[i..(i + m - 1)] == str2. - If
str1[i] == 'F', the substring ofwordwith sizemstarting at indexiis not equal tostr2, i.e.,word[i..(i + m - 1)] != str2.
Return the lexicographically smallest possible string that can be generated by str1 and str2. If no string can be generated, return an empty string "".
Example 1:
Input: str1 = "TFTF", str2 = "ab"
Output: "ababa"
Explanation:
The table below represents the string "ababa"
Index T/F Substring of length m
0 'T' "ab"
1 'F' "ba"
2 'T' "ab"
3 'F' "ba"
The strings "ababa" and "ababb" can be generated by str1 and str2.
Return "ababa" since it is the lexicographically smaller string.
Example 2:
Input: str1 = "TFTF", str2 = "abc"
Output: ""
Explanation:
No string that satisfies the conditions can be generated.
Example 3:
Input: str1 = "F", str2 = "d"
Output: "a"
Constraints:
1 <= n == str1.length <= 10^41 <= m == str2.length <= 500str1consists only of'T'or'F'.str2consists only of lowercase English characters.
Solution
Approach: Greedy
Write s = str1 and t = str2. Start with the string ans of length n + m - 1 filled with 'a', the smallest letter, and a fixed array that marks positions forced by a rule.
- For every
'T'at indexi, writetintoans[i..i+m-1]. If a fixed position already holds a different letter, no string works: return"". Mark the positions as fixed. - For every
'F'at indexi, ifans[i..i+m-1]currently equalst, one of its letters must change. Change the last position in that window that is not fixed to'b'(the smallest letter that differs from the'a'there, and the last position keeps the string as small as possible). If every position is fixed, return"".
Return ans.
Complexity: O(nm) time, O(n + m) space.
class Solution:
def generateString(self, s: str, t: str) -> str:
n, m = len(s), len(t)
ans = ["a"] * (n + m - 1)
fixed = [False] * (n + m - 1)
for i, b in enumerate(s):
if b != "T":
continue
for j, c in enumerate(t):
k = i + j
if fixed[k] and ans[k] != c:
return ""
ans[k] = c
fixed[k] = True
for i, b in enumerate(s):
if b != "F":
continue
if "".join(ans[i : i + m]) != t:
continue
for j in range(i + m - 1, i - 1, -1):
if not fixed[j]:
ans[j] = "b"
break
else:
return ""
return "".join(ans)