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 expression = "{a,b}{c,d}" {a,b} {c,d} Group 1 a b Group 2 c d Grammar Rules: • Union: {a,b} = set of a, b • Concat: {a}{b} = cartesian • Result: sorted, no duplicates Operation: CONCATENATION X 2 x 2 = 4 combinations ALGORITHM STEPS 1 Parse Expression Identify groups: {a,b}, {c,d} 2 Expand Unions Group1: [a,b], Group2: [c,d] 3 Cartesian Product Concatenate all pairs X c d a ac ad b bc bd 4 Sort and Dedupe Use Set, then sort result FINAL RESULT Sorted Output Array: ac ad bc bd [0] [1] [2] [3] ["ac","ad","bc","bd"] OK - 4 unique strings Expansion Tree: {a,b}{c,d} a{c,d} b{c,d} ac ad bc bd Key Insight: Use recursive parsing with two operations: UNION (comma-separated in braces) expands to set union, CONCATENATION (adjacent groups) produces cartesian product. Use a Set to remove duplicates, then sort the final result. Time complexity: O(n * 2^n) where n is expression length. TutorialsPoint - Brace Expansion II | Optimal Solution (Recursive Parsing)
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