#3474
Lexicographically Smallest Generated String
HardStringGreedyString MatchingGreedyString Manipulation
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)
Use a greedy approach to build the result string by filling in the constraints from str1 while ensuring the smallest lexicographical order.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty result string.
- 2Step 2: Iterate through str1, appending str2 or the smallest lexicographical character as needed.
- 3Step 3: Ensure that 'F' conditions are satisfied by checking against str2.
solution.py9 lines
1def generate_strings(str1, str2):
2 n, m = len(str1), len(str2)
3 result = [''] * (n + m - 1)
4 for i in range(n):
5 if str1[i] == 'T':
6 result[i:i + m] = str2
7 elif result[i:i + m] == list(str2):
8 return ''
9 return ''.join(result)ℹ
Complexity note: Linear time complexity due to a single pass through str1 and filling the result array.
- 1Understanding how 'T' and 'F' conditions affect string generation.
- 2Lexicographical order can be maintained by careful character placement.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.