Brace Expansion Problem
Description
LeetCode Problem 1087.
You are given a string s representing a list of words. Each letter in the word has one or more options.
- If there is one option, the letter is represented as is.
- If there is more than one option, then curly braces delimit the options. For example,
"{a,b,c}"represents options["a", "b", "c"].
For example, if s = "a{b,c}", the first character is always 'a', but the second character can be 'b' or 'c'. The original list is ["ab", "ac"].
Return all words that can be formed in this manner, sorted in lexicographical order.
Example 1:
Input: s = "{a,b}c{d,e}f"
Output: ["acdf","acef","bcdf","bcef"]
Example 2:
Input: s = "abcd"
Output: ["abcd"]
Constraints:
1 <= s.length <= 50sconsists of curly brackets'{}', commas',', and lowercase English letters.sis guaranteed to be a valid input.- There are no nested curly brackets.
- All characters inside a pair of consecutive opening and ending curly brackets are different.
Solution
Approach: Parse into Groups, then Backtrack
First turn s into a list of groups, one per position of the output word. A letter outside braces is a group with one option. {...} is a group with the letters inside it (skip the commas). There is no nesting, so finding the next } is enough. For "{a,b}c{d,e}f" the groups are [a, b], [c], [d, e], [f].
Then build words with backtracking: for group k, try each of its options at position k and recurse to group k + 1. When all groups are filled, add the word to the answer.
The output has to be sorted, but if we sort the options inside every group first, no final sort is needed. All words have the same length, and backtracking tries the first position's options in order, then the second position's options in order for each of them, and so on. That is exactly lexicographic order.
Complexity: O(W · L) time and space for the output, where W is the number of words and L is their length, plus O(n) to parse s.
class Solution:
def expand(self, s: str) -> List[str]:
# Split s into groups of options: "{b,a}c" -> [["a", "b"], ["c"]].
groups = []
i = 0
while i < len(s):
if s[i] == "{":
j = s.index("}", i)
groups.append(sorted(s[i + 1 : j].split(",")))
i = j + 1
else:
groups.append([s[i]])
i += 1
# Pick one option per group. Every word has the same length and each group is
# tried in sorted order, so the words come out already sorted.
ans = []
word = []
def dfs(k: int) -> None:
if k == len(groups):
ans.append("".join(word))
return
for c in groups[k]:
word.append(c)
dfs(k + 1)
word.pop()
dfs(0)
return ans