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
Brace Expansion II: Input → Output TransformationInput Expression{a,b}{c,d}Braces with unionsParse & Expand{a,b} → [a,b]{c,d} → [c,d]Cartesian productOutput WordsacadbcbdSorted & UniqueGrammar Rules Applied1. Union: {a,b} creates set {a,b}2. Union: {c,d} creates set {c,d}3. Concatenation: {a,b} × {c,d} = {ac,ad,bc,bd}4. Sort result: ["ac","ad","bc","bd"]🎯 All possible combinations generated and sorted!
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
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 25
23.2K Views
Medium Frequency
~35 min Avg. Time
892 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