Brace Expansion - Problem
Brace Expansion is a fascinating string manipulation problem where you need to generate all possible combinations from a template string containing options.
Given a string
• Single option: Regular characters like
• Multiple options: Curly braces
Example: The template
• First position: always
• Second position: either
• Third position: always
Return all possible words in lexicographical order.
Given a string
s that represents a template with choices, your task is to expand it into all possible words:• Single option: Regular characters like
'a' remain as-is• Multiple options: Curly braces
{a,b,c} represent choices between 'a', 'b', or 'c'Example: The template
"a{b,c}d" expands to ["abd", "acd"] because:• First position: always
'a'• Second position: either
'b' or 'c'• Third position: always
'd'Return all possible words in lexicographical order.
Input & Output
example_1.py — Basic Case
$
Input:
s = "a{b,c}"
›
Output:
["ab", "ac"]
💡 Note:
The string has 'a' fixed at position 0, and position 1 can be either 'b' or 'c'. This generates two combinations: 'ab' and 'ac', sorted lexicographically.
example_2.py — Multiple Choice Groups
$
Input:
s = "{a,b}{c,d}"
›
Output:
["ac", "ad", "bc", "bd"]
💡 Note:
Position 0 can be 'a' or 'b', position 1 can be 'c' or 'd'. All combinations: ac, ad, bc, bd. Already in lexicographical order.
example_3.py — Mixed Fixed and Choice
$
Input:
s = "a{b,c}d{e,f}"
›
Output:
["abde", "abdf", "acde", "acdf"]
💡 Note:
Positions 0 and 2 are fixed ('a' and 'd'), while positions 1 and 3 have choices. This creates 2×2=4 total combinations.
Visualization
Tap to expand
Understanding the Visualization
1
📋 Parse Design Template
Break down 'a{b,c}d' into: fixed 'a', choice {b,c}, fixed 'd'
2
🏭 Production Line Setup
Set up stations: Station 1 (add 'a'), Station 2 (choose b or c), Station 3 (add 'd')
3
⚡ Generate Combinations
Each T-shirt goes through all stations, creating 'abd' and 'acd'
4
📦 Sort and Package
Arrange final products in alphabetical order: ['abd', 'acd']
Key Takeaway
🎯 Key Insight: Think of brace expansion as a production line where each position is a station that either adds a fixed element or branches into multiple paths for choices.
Time & Space Complexity
Time Complexity
O(N * M)
N combinations generated, each taking O(M) time to construct
✓ Linear Growth
Space Complexity
O(N * M + D)
N*M for results, D for recursion depth (string length)
✓ Linear Space
Constraints
- 1 ≤ s.length ≤ 50
-
s consists of lowercase English letters and characters
'{', '}', ',' - All the values that are split by comma are single characters
- Guaranteed valid input: braces are properly matched and formatted
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code