1096. Brace Expansion II
SourceWeekly Contest 142 Q4DifficultyHardRating2348
Description
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.
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.
Solutions
Solution 1: Recursion
Thinking
The expression mixes union, concatenation, and nested braces. Length \(\le 60\) lets us expand the innermost brace, splice, and recurse.
Find the first } and its matching {. Prefix \(a\), each alternative \(b_i\), and suffix \(c\) become \(a+b_i+c\). A brace-free string is inserted into a set.
The set is sorted for the answer.
Define a recursive function \(\textit{dfs}(\textit{exp})\) that expands \(\textit{exp}\) and stores every word in a set \(s\).
Find the index \(j\) of the first }. If there is none, \(\textit{exp}\) is already a single word, so insert it into \(s\).
Otherwise search left from \(j\) for the matching { at index \(i\). The prefix \(\textit{exp}[:i]\) and the suffix \(\textit{exp}[j + 1:]\) are \(a\) and \(c\). Split the brace body \(\textit{exp}[i + 1: j]\) on commas into \(b_1, b_2, \cdots, b_k\), and recurse on \(\textit{dfs}(a + b_i + c)\) for each \(b_i\). The first } always closes a brace group with no nested braces, so splitting that body on commas is exact.
Sort \(s\) in lexicographical order to obtain the answer.
The time complexity is \(O(3^{n/6})\), and the space complexity is \(O(n 3^{n/7})\), where \(n\) is the length of \(\textit{expression}\). The worst-case time comes from a nested three-way union such as \(\{\ldots\{a,b,c\},a,b\}\): every extra \(6\) characters multiplies the recursion tree by about \(3\), and the total length of the strings processed is \(\Theta(3^{n/6})\). Concatenating copies of \(\{a,b,c\}\) produces \(\Theta(3^{n/7})\) words of length \(O(n)\). The deduplicated set occupies \(O(n 3^{n/7})\) space, and sorting it costs \(O(n^2 3^{n/7})\), which is within the time bound above. The recursion depth is \(O(n)\), so the strings on the stack use \(O(n^2)\) extra space.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
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 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
Solution 2: Grammar Parsing
Thinking
Solution 1 copies the still-unexpanded suffix into every alternative. A nested three-way union such as \(\{\ldots\{a,b,c\},a,b\}\) therefore repeats the same suffix and takes \(O(3^{n/6})\) time, even when only a constant number of words are distinct.
Commas occur only inside braces and mean union. Adjacent factors outside commas mean concatenation. A left-to-right parse evaluates each subexpression once.
A factor is a run of lowercase letters or a brace expression. Concatenation is the Cartesian product of the current set with the factor, and commas take the union of those products. A hash set removes duplicates, and the final set is sorted.
Let \(s\) be the expression. Starting at index \(i\), define two functions.
\(\textit{expr}(i)\) parses a union of terms. It parses one \(\textit{term}\), and while the next character is a comma it skips the comma, parses another \(\textit{term}\), and unions the sets together. It stops at } or the end of \(s\).
\(\textit{term}(i)\) parses a concatenation of factors, starting from \(\{\varepsilon\}\). A { recursively parses the inner \(\textit{expr}\) and then skips the matching }. Otherwise the factor is the following run of lowercase letters. The current set is replaced by its Cartesian product with that factor. The function returns at a comma, a }, or the end of \(s\).
Sort the set returned by \(\textit{expr}(0)\). Each subexpression is parsed once, so the suffix is no longer copied and rescanned on every branch.
The time complexity is \(O(n^2 3^{n/7})\), and the space complexity is \(O(n 3^{n/7})\), where \(n\) is the length of the expression. The worst case is a concatenation of {a,b,c} groups, which produces \(\Theta(3^{n/7})\) words of length \(O(n)\). Building them costs \(O(n 3^{n/7})\) and sorting them costs \(O(n^2 3^{n/7})\). A nested three-way union keeps every intermediate set at size \(O(1)\), so that input takes only \(O(n)\) time.
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 | |
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 41 42 43 44 45 46 47 48 49 | |
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 41 42 43 44 45 46 47 48 49 50 | |
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 41 42 43 44 45 46 47 48 49 | |
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 | |