LeetCode Problem Workspace

Lexicographically Smallest Generated String

Generate the lexicographically smallest string by merging str1 and str2 using a greedy approach with invariant checks.

category

3

Topics

code_blocks

5

Code langs

hub

3

Related

Practice Focus

Hard · Greedy choice plus invariant validation

bolt

Answer-first summary

Generate the lexicographically smallest string by merging str1 and str2 using a greedy approach with invariant checks.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Greedy choice plus invariant validation

Try AiBox Copilotarrow_forward

This problem requires building a string from str1 and str2 that satisfies position constraints while keeping it lexicographically minimal. Start with the smallest available character at each step, validating that the chosen character preserves the generation rules. Dynamic programming can help track feasible positions and ensure the greedy choices do not lead to dead ends.

Problem Statement

Given two strings str1 and str2 of lengths n and m, generate a string word of length n + m - 1 by placing characters from str2 at positions indicated by 'T' in str1, while keeping other positions lexicographically minimal. Each index 0 <= i <= n - 1 of str1 determines constraints on the generated string: 'T' requires alignment with str2 and 'F' allows any character.

Return the lexicographically smallest string that can be generated following these rules. If no valid string exists under the constraints, return an empty string "". Examples: for str1 = "TFTF" and str2 = "ab", output is "ababa"; for str1 = "TFTF" and str2 = "abc", output is "".

Examples

Example 1

Input: str1 = "TFTF", str2 = "ab"

Output: "ababa"

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: ""

No string that satisfies the conditions can be generated.

Example 3

Input: str1 = "F", str2 = "d"

Output: "a"

Example details omitted.

Constraints

  • 1 <= n == str1.length <= 104
  • 1 <= m == str2.length <= 500
  • str1 consists only of 'T' or 'F'.
  • str2 consists only of lowercase English characters.

Solution Approach

Greedy Character Selection

Iterate through the target string positions, always choosing the smallest character from str2 when a 'T' occurs and the minimal available character otherwise. Ensure each choice preserves future feasibility to maintain lexicographical order.

Invariant Validation

After each greedy choice, check that the remaining part of str2 can still be aligned according to str1's 'T' positions. This avoids dead-end configurations where a valid string cannot be completed.

Dynamic Programming Tracking

Use DP to record which suffixes of str2 can match future 'T' positions in str1. This enables constant-time validation of each greedy selection and ensures that the lexicographical minimum is achievable.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Time complexity depends on iterating through str1 and validating positions, roughly O(n * m) for DP checks. Space complexity is O(n * m) for storing valid suffix states.

What Interviewers Usually Probe

  • Check if the candidate string preserves alignment with str2 at 'T' positions.
  • Ensure each greedy choice does not prevent future valid placements.
  • Consider edge cases where str2 cannot fully match str1's 'T' positions.

Common Pitfalls or Variants

Common pitfalls

  • Choosing the smallest character without validating future feasibility may produce an invalid string.
  • Ignoring alignment of str2 with 'T' positions can lead to an incorrect empty string result.
  • Not accounting for all suffixes in DP may miss possible valid lexicographically smaller strings.

Follow-up variants

  • Change str1 to include multiple character types instead of just 'T' and 'F'.
  • Allow str2 to contain uppercase letters and verify case-sensitive minimal string.
  • Ask for the k-th lexicographically smallest generated string instead of the minimal one.

FAQ

What does lexicographically smallest mean in this problem?

It means selecting characters at each position to create the earliest string in dictionary order while satisfying str1's constraints.

Why use dynamic programming with greedy choice?

DP tracks which suffixes of str2 remain feasible, ensuring that each greedy pick does not prevent completing a valid string.

What should I return if no valid string can be generated?

Return an empty string "" if str2 cannot align with all 'T' positions in str1.

Can str2 have repeated characters?

Yes, repeated characters are allowed; the algorithm must still select the smallest lexicographical sequence.

How does the greedy plus invariant pattern apply here?

The pattern ensures each step chooses the smallest character while checking that remaining positions can still satisfy str1 constraints.

terminal

Solution

Solution 1: Greedy

Let $str1$ be $s$ and $str2$ be $t$.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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)
Lexicographically Smallest Generated String Solution: Greedy choice plus invariant validati… | LeetCode #3474 Hard