Skip to main content

Lexicographically Smallest Generated String - Solution & Explanation

HardStringGreedyString Matching12 min readAsked at: Amazon, Microsoft, Barclays +2
Practice this 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.

Approach Overview

Problem Overview: You need to generate the lexicographically smallest string that satisfies a set of constraints describing which substrings must match or must not match a given pattern. The challenge is balancing correctness with lexicographic minimality while enforcing substring conditions efficiently.

Approach 1: Brute Force Generation with Validation (Exponential time, O(k^n) time, O(n) space)

Start by generating candidate strings character by character from the alphabet (typically 'a' to 'z'). For each fully built string, check whether all substring constraints are satisfied. Validation usually involves comparing substrings against the pattern directly. While this approach guarantees correctness, the search space grows exponentially and quickly becomes infeasible for realistic input sizes.

This brute force method helps clarify the problem: you must satisfy matching rules while minimizing lexicographic order. However, repeatedly rebuilding and checking substrings results in excessive work, making it unsuitable beyond very small inputs.

Approach 2: Greedy Construction with String Matching (O(n + m) time, O(n) space)

The optimal strategy builds the answer from left to right using a greedy rule: always place the smallest possible character that keeps the constraints satisfiable. Instead of repeatedly comparing substrings, use efficient string matching techniques such as the KMP prefix function to track how much of the pattern currently matches.

When a constraint requires a specific substring match, the algorithm forces those characters into the result. For positions without strict requirements, try characters from 'a' upward and verify that placing them does not create a forbidden pattern match. The prefix-function state lets you update matches in constant time per character.

This combination of greedy selection and incremental string matching ensures that each position is processed once while maintaining correctness. The greedy rule guarantees lexicographic minimality because you only choose larger characters when smaller ones would violate constraints.

Recommended for interviews: Interviewers expect the greedy + string matching approach. Starting with brute force shows you understand the constraints, but the optimized solution demonstrates knowledge of prefix functions and efficient substring checking—key skills for advanced string problems.

Solution

Let str1 be s and str2 be t.

We can use a string ans of length n + m - 1 to store the generated string, where each character of ans is initially set to 'a'. We also need a boolean array fixed of length n + m - 1 to record which positions in ans have already been fixed.

First, we iterate through the string s. For each index i, if s[i] is 'T', we need to set the substring of ans starting at index i with length m to t. During this process, if we find that a position has already been fixed and the character does not match the corresponding character in t, it means it is impossible to generate a valid string, so we return an empty string immediately.

Next, we iterate through s again. For each index i, if s[i] is 'F', we need to check whether the substring of ans starting at index i with length m is equal to t. If it is, we need to find a position in this substring and change its character to 'b' (since 'b' is lexicographically greater than 'a'), to ensure this substring is not equal to t. If we cannot find such a position, it means it is impossible to generate a valid string, so we return an empty string immediately.

Finally, we concatenate the characters in ans into a string and return it.

The time complexity is O(n times m), and the space complexity is O(n + m).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force GenerationO(k^n)O(n)Useful only for understanding constraints or very small inputs
Greedy + String Matching (KMP)O(n + m)O(n)General optimal solution; efficient substring validation during construction

Video Solution

Lexicographically Smallest Generated String | Simplified Approach | Dry Run | Leetcode 3474 • codestorywithMIK • 11,626 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Lexicographically Smallest Generated String easy or hard?
LeetCode classifies this problem as Hard because it mixes greedy construction with advanced string matching techniques. Understanding lexicographic ordering alone is not enough; you must also maintain efficient substring validation to avoid quadratic behavior.
Lexicographically Smallest Generated String Python/Java solution
A typical implementation builds the result string incrementally while maintaining the KMP prefix state. The same logic works across Python, Java, C++, and Go because it relies on simple arrays and character comparisons. Each step tries the smallest possible character that preserves the matching constraints.
How to solve Lexicographically Smallest Generated String in O(n)?
Process the string from left to right and maintain the current pattern match length using a prefix-function (KMP). For each position, try characters from 'a' upward and check whether adding the character preserves all required or forbidden substring conditions. Because match transitions are constant time, the total work remains linear.
What is the best approach for Lexicographically Smallest Generated String?
The best approach combines greedy construction with a string matching algorithm such as KMP. Build the string left to right and always try the smallest character that keeps all constraints valid. The prefix-function from KMP allows constant-time updates of the current match state, producing an overall O(n + m) solution.
Is Lexicographically Smallest Generated String asked at Google/Amazon/Meta?
Hard string construction and greedy matching problems frequently appear in interviews at companies like Google, Amazon, and Meta. Variants that involve lexicographic minimization with pattern constraints are especially common in senior-level interviews because they test both greedy reasoning and string algorithms.
What data structure is used in Lexicographically Smallest Generated String?
The solution primarily uses arrays and prefix-function tables from the KMP string matching algorithm. These structures track partial matches of the pattern as the string is constructed. Combined with greedy character selection, they allow efficient constraint checking.
What is the time complexity of Lexicographically Smallest Generated String?
The optimal solution runs in O(n + m) time, where n is the length of the generated string and m is the pattern length. Using a prefix-function or similar string matching structure avoids repeated substring comparisons. Space complexity is typically O(n) for storing the result and auxiliary arrays.

Ready to solve this problem?

Practice Lexicographically Smallest Generated String with our built-in code editor and test cases.

Practice on FleetCode