Brace Expansion II - Problem
Under a specific grammar, strings can represent a set of lowercase words. Given an expression following this grammar, return the sorted list of words that the expression represents.
The grammar rules are:
- Single letters:
R("a") = {"a"} - Union (comma-separated):
R("{a,b,c}") = {"a","b","c"} - Concatenation:
R("{a,b}{c,d}") = {"ac","ad","bc","bd"}
More complex example: R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}
Note that union removes duplicates, so R("{{a,b},{b,c}}") = {"a","b","c"}
Input & Output
Example 1 — Basic Union and Concatenation
$
Input:
expression = "{a,b}{c,d}"
›
Output:
["ac","ad","bc","bd"]
💡 Note:
First group {a,b} gives {a,b}, second group {c,d} gives {c,d}. Cartesian product: a×{c,d} = {ac,ad}, b×{c,d} = {bc,bd}. Final result sorted: ["ac","ad","bc","bd"]
Example 2 — Nested Braces with Duplicates
$
Input:
expression = "{{a,b},{b,c}}"
›
Output:
["a","b","c"]
💡 Note:
Inner group {a,b} gives {a,b}, inner group {b,c} gives {b,c}. Union of both groups: {a,b} ∪ {b,c} = {a,b,c}. Duplicates removed, sorted: ["a","b","c"]
Example 3 — Complex Mixed Expression
$
Input:
expression = "a{b,c}{d,e}f"
›
Output:
["abdf","abef","acdf","acef"]
💡 Note:
Start with 'a'. Group {b,c} gives {b,c}. Concatenate: a×{b,c} = {ab,ac}. Group {d,e} gives {d,e}. Concatenate: {ab,ac}×{d,e} = {abd,abe,acd,ace}. Finally add 'f': {abdf,abef,acdf,acef}
Constraints
- 1 ≤ expression.length ≤ 60
- expression[i] consists of '{', '}', ',', and lowercase English letters
- The given expression represents a set of words based on the grammar given in the description
Visualization
Tap to expand
Understanding the Visualization
1
Input
Brace expression with unions and concatenations
2
Parse
Identify braces, commas, and characters
3
Expand
Generate all possible combinations
4
Output
Sorted unique words
Key Takeaway
🎯 Key Insight: Parse nested braces recursively, combining sets with union and concatenation operations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code