LeetCode #3474 — HARD

Lexicographically Smallest Generated String

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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 of word with size m starting at index i is equal to str2, i.e., word[i..(i + m - 1)] == str2.
  • If str1[i] == 'F', the substring of word with size m starting at index i is not equal to str2, 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 <= 104
  • 1 <= m == str2.length <= 500
  • str1 consists only of 'T' or 'F'.
  • str2 consists only of lowercase English characters.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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 of word with size m starting at index i is equal to str2, i.e., word[i..(i + m - 1)] == str2. If str1[i] == 'F', the substring of word with size m starting at index i is not equal to str2, 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 "".

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Greedy · String Matching

Example 1

"TFTF"
"ab"

Example 2

"TFTF"
"abc"

Example 3

"F"
"d"

Related Problems

  • Lexicographically Smallest Equivalent String (lexicographically-smallest-equivalent-string)
Step 02

Core Insight

What unlocks the optimal approach

  • Use dynamic programming.
  • Fill the fixed part.
  • Use KMP's next table for DP.
  • The state is the prefix length and the longest suffix length that matches the pattern.
  • Each unknown character can be selected from <code>['a', 'b']</code>.
  • Can you think of a greedy approach?
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3474: Lexicographically Smallest Generated String
class Solution {
  public String generateString(String str1, String str2) {
    final int n = str1.length();
    final int m = str2.length();
    final int sz = n + m - 1;
    char[] ans = new char[sz];
    boolean[] modifiable = new boolean[sz];
    Arrays.fill(modifiable, true);

    // 1. Handle all 'T' positions first.
    for (int i = 0; i < n; ++i)
      if (str1.charAt(i) == 'T')
        for (int j = 0; j < m; ++j) {
          final int pos = i + j;
          if (ans[pos] != 0 && ans[pos] != str2.charAt(j))
            return "";
          ans[pos] = str2.charAt(j);
          modifiable[pos] = false;
        }

    // 2. Fill all remaining positions with 'a'.
    for (int i = 0; i < sz; ++i)
      if (ans[i] == 0)
        ans[i] = 'a';

    // 3. Handle all 'F' positions.
    for (int i = 0; i < n; ++i)
      if (str1.charAt(i) == 'F' && match(ans, i, str2)) {
        final int modifiablePos = lastModifiablePosition(i, m, modifiable);
        if (modifiablePos == -1)
          return "";
        ans[modifiablePos] = 'b';
        modifiable[modifiablePos] = false;
      }

    return new String(ans);
  }

  // Returns true if the substring of ans starting at `i` matches `s`.
  private boolean match(char[] ans, int i, String s) {
    for (int j = 0; j < s.length(); ++j)
      if (ans[i + j] != s.charAt(j))
        return false;
    return true;
  }

  // Finds the last modifiable position in the substring ans starting at `i`.
  private int lastModifiablePosition(int i, int m, boolean[] modifiable) {
    int modifiablePos = -1;
    for (int j = 0; j < m; ++j) {
      final int pos = i + j;
      if (modifiable[pos])
        modifiablePos = pos;
    }
    return modifiablePos;
  }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n log n)
Space
O(1)

Approach Breakdown

EXHAUSTIVE
O(2ⁿ) time
O(n) space

Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.

GREEDY
O(n log n) time
O(1) space

Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.

Shortcut: Sort + single pass → O(n log n). If no sort needed → O(n). The hard part is proving it works.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.