Brace Expansion II
HardUpdated: Aug 2, 2025
Practice on:
Problem
Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents.
The grammar can best be understood through simple examples:
- Single letters represent a singleton set containing that word.
R("a") = {"a"}R("w") = {"w"}- When we take a comma-delimited list of two or more expressions, we take the union of possibilities.
R("{a,b,c}") = {"a","b","c"}R("{{a,b},{b,c}}") = {"a","b","c"}(notice the final set only contains each word at most once)- When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.
R("{a,b}{c,d}") = {"ac","ad","bc","bd"}R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}
Formally, the three rules for our grammar:
- For every lowercase letter
x, we haveR(x) = {x}. - For expressions
e1, e2, ... , ekwithk >= 2, we haveR({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ... - For expressions
e1ande2, we haveR(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where+denotes concatenation, and×denotes the cartesian product.
Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.
Examples
Example 1
Input: expression = "{a,b}{c,{d,e}}"
Output: ["ac","ad","ae","bc","bd","be"]
Example 2
Input: expression = "{{a,z},a{b,c},{ab,z}}"
Output: ["a","ab","ac","z"]
Explanation: Each distinct word is written only once in the final answer.
Constraints
1 <= expression.length <= 60expression[i]consists of'{','}',','or lowercase English letters.- The given
expressionrepresents a set of words based on the grammar given in the description.
Solution
Method 1 – Recursive Backtracking with Set
Intuition
The problem is to expand a string with nested braces and unions into all possible unique words. We use recursion to handle nested braces and sets to avoid duplicates. At each level, we parse the string, handling unions (,), concatenations, and nested braces.
Approach
- Define a recursive function to parse the string from a given index.
- For each character:
- If
{, recursively parse the subexpression inside the braces. - If
,, treat as a union: merge the current set into the result and start a new set. - If a letter, treat as a singleton set and concatenate with the current set.
- If
- After parsing, merge all sets and return the sorted list of unique words.
Code
C++
class Solution {
public:
set<string> dfs(const string& s, int& i) {
set<string> res, cur = {""};
while (i < s.size() && s[i] != '}') {
if (s[i] == '{') {
++i;
set<string> t = dfs(s, i);
set<string> tmp;
for (auto& a : cur) for (auto& b : t) tmp.insert(a + b);
cur = tmp;
} else if (s[i] == ',') {
for (auto& a : cur) res.insert(a);
cur = {""};
++i;
} else {
set<string> tmp;
for (auto& a : cur) tmp.insert(a + s[i]);
cur = tmp;
++i;
}
}
for (auto& a : cur) res.insert(a);
++i;
return res;
}
vector<string> braceExpansionII(string s) {
int i = 0;
set<string> ans = dfs(s, i);
return vector<string>(ans.begin(), ans.end());
}
};
Go
func braceExpansionII(s string) []string {
var dfs func([]byte, *int) map[string]struct{}
dfs = func(s []byte, i *int) map[string]struct{} {
res := map[string]struct{}{}
cur := map[string]struct{}{ "": {} }
for *i < len(s) && s[*i] != '}' {
if s[*i] == '{' {
*i++
t := dfs(s, i)
tmp := map[string]struct{}{}
for a := range cur {
for b := range t {
tmp[a+b] = struct{}{}
}
}
cur = tmp
} else if s[*i] == ',' {
for a := range cur { res[a] = struct{}{} }
cur = map[string]struct{}{ "": {} }
*i++
} else {
tmp := map[string]struct{}{}
for a := range cur {
tmp[a+string(s[*i])] = struct{}{}
}
cur = tmp
*i++
}
}
for a := range cur { res[a] = struct{}{} }
*i++
return res
}
i := 0
ans := dfs([]byte(s), &i)
res := make([]string, 0, len(ans))
for k := range ans { res = append(res, k) }
sort.Strings(res)
return res
}
Java
class Solution {
public List<String> braceExpansionII(String s) {
Set<String> ans = dfs(s, new int[]{0});
List<String> res = new ArrayList<>(ans);
Collections.sort(res);
return res;
}
private Set<String> dfs(String s, int[] i) {
Set<String> res = new HashSet<>(), cur = new HashSet<>();
cur.add("");
while (i[0] < s.length() && s.charAt(i[0]) != '}') {
if (s.charAt(i[0]) == '{') {
i[0]++;
Set<String> t = dfs(s, i);
Set<String> tmp = new HashSet<>();
for (String a : cur) for (String b : t) tmp.add(a + b);
cur = tmp;
} else if (s.charAt(i[0]) == ',') {
res.addAll(cur);
cur = new HashSet<>(); cur.add("");
i[0]++;
} else {
Set<String> tmp = new HashSet<>();
for (String a : cur) tmp.add(a + s.charAt(i[0]));
cur = tmp;
i[0]++;
}
}
res.addAll(cur);
i[0]++;
return res;
}
}
Kotlin
class Solution {
fun braceExpansionII(s: String): List<String> {
fun dfs(s: String, i: IntArray): Set<String> {
var cur = setOf("")
var res = setOf<String>()
while (i[0] < s.length && s[i[0]] != '}') {
when (s[i[0]]) {
'{' -> {
i[0]++
val t = dfs(s, i)
cur = cur.flatMap { a -> t.map { b -> a + b } }.toSet()
}
',' -> {
res = res + cur
cur = setOf("")
i[0]++
}
else -> {
cur = cur.map { it + s[i[0]] }.toSet()
i[0]++
}
}
}
res = res + cur
i[0]++
return res
}
val ans = dfs(s, intArrayOf(0))
return ans.sorted()
}
}
Python
class Solution:
def braceExpansionII(self, s: str) -> list[str]:
def dfs(i: int) -> tuple[set[str], int]:
res, cur = set(), {""}
while i < len(s) and s[i] != '}':
if s[i] == '{':
t, i = dfs(i+1)
cur = {a+b for a in cur for b in t}
elif s[i] == ',':
res |= cur
cur = {""}
i += 1
else:
cur = {a+s[i] for a in cur}
i += 1
res |= cur
return res, i+1
ans, _ = dfs(0)
return sorted(ans)
Rust
impl Solution {
pub fn brace_expansion_ii(s: String) -> Vec<String> {
fn dfs(s: &[u8], i: &mut usize) -> std::collections::BTreeSet<String> {
let mut res = std::collections::BTreeSet::new();
let mut cur = std::collections::BTreeSet::new();
cur.insert(String::new());
while *i < s.len() && s[*i] != b'}' {
if s[*i] == b'{' {
*i += 1;
let t = dfs(s, i);
let mut tmp = std::collections::BTreeSet::new();
for a in &cur {
for b in &t {
tmp.insert(format!("{}{}", a, b));
}
}
cur = tmp;
} else if s[*i] == b',' {
res.append(&mut cur);
cur = std::collections::BTreeSet::new();
cur.insert(String::new());
*i += 1;
} else {
let mut tmp = std::collections::BTreeSet::new();
for a in &cur {
tmp.insert(format!("{}{}", a, s[*i] as char));
}
cur = tmp;
*i += 1;
}
}
res.append(&mut cur);
*i += 1;
res
}
let mut i = 0;
dfs(s.as_bytes(), &mut i).into_iter().collect()
}
}
Complexity
- ⏰ Time complexity:
O(2^n * n)— n is the length of the string, due to all possible combinations. - 🧺 Space complexity:
O(2^n * n)— For storing all unique words.