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 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
🎨 T-Shirt Design Factory: a{b,c}d📋 Template ParserInput: a{b,c}dTokens: [a, {b,c}, d]🏭 Station 1Add: 'a'Result: "a"🏭 Station 2Choice: {b,c}Path 1: "ab"Path 2: "ac"🏭 Station 3Add: 'd'Final Products📦 Final Products (Sorted)👕 "abd"👕 "acd"
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

n
2n
Linear Growth
Space Complexity
O(N * M + D)

N*M for results, D for recursion depth (string length)

n
2n
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
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
42.8K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen