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 have R(x) = {x}.
  • For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ...
  • For expressions e1 and e2, we have R(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

1
2
Input: expression = "{a,b}{c,{d,e}}"
Output: ["ac","ad","ae","bc","bd","be"]

Example 2

1
2
3
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 <= 60
  • expression[i] consists of '{', '}', ','or lowercase English letters.
  • The given expression represents 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

  1. Define a recursive function to parse the string from a given index.
  2. 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.
  3. After parsing, merge all sets and return the sorted list of unique words.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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());
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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.