Under a grammar given below, strings can represent a set of lowercase words.  Let's use R(expr) to denote the set of words the expression represents.
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 2 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 3 rules for our grammar:

For every lowercase letter x, we have R(x) = {x}
For expressions e_1, e_2, ... , e_k with k >= 2, we have R({e_1,e_2,...}) = R(e_1) ∪ R(e_2) ∪ ...
For expressions e_1 and e_2, we have R(e_1 + e_2) = {a + b for (a, b) in R(e_1) × R(e_2)}, 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: "{a,b}{c,{d,e}}"
Output: ["ac","ad","ae","bc","bd","be"]


Example 2:
Input: "{{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.

Difficulty: interview

Starter code:

class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        

Solutions:
class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
     
        stack,res,cur=[],[],['']
        for v in expression:
           
            if v.isalpha():
                cur=[c+v for c in cur]
            elif v==',':
                res+=cur
                cur=['']
            elif v=='{':
                stack.append(res)
                stack.append(cur)
                res,cur=[],['']
            elif v=='}':
                preCur=stack.pop()
                preRes=stack.pop()
                cur=[p+c for p in preCur for c in res+cur]
                res=preRes
        return sorted(set(res+cur))

class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        groups = [[]]
        level = 0
        for i, c in enumerate(expression):
            if c == '{':
                if level == 0:
                    start = i+1
                level += 1
            elif c == '}':
                level -= 1
                if level == 0:
                    groups[-1].append(self.braceExpansionII(expression[start:i]))
            elif level == 0:
                if c == \",\":
                    groups.append([])
                else:
                    groups[-1].append([c])
                
        return sorted(set().union(*[set(map(''.join, itertools.product(*group))) for group in groups]))


class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        stack = []
        prev = set()
        curr = set()
        for s in expression:
            if s == '{':
                stack.append(prev)
                stack.append(curr)
                curr = set()
                prev = set()
            elif s == '}':
                k = stack.pop()
                p = set()
                for i in k or ['']:
                    for j in prev | curr:
                        p.add(i + j)
                prev = stack.pop()
                curr = p
            elif s == ',':
                prev |= curr
                curr = set()
            else:
                p = set()
                for c in curr or ['']:
                    p.add(c + s)
                curr = p
        return list(sorted(curr))

class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        stack,res,cur=[],[],['']
        for i,v in enumerate(expression):
            print(v)
            print(stack)
            print(res,cur)
            if v.isalpha():
                cur=[c+v for c in cur]

            elif v=='{':
                stack.append(res)
                stack.append(cur)
                res,cur=[],['']
            elif v=='}':
                precur=stack.pop()
                preres=stack.pop()
                cur=[p+c for p in precur for c in res+cur]
                res=preres
            elif v==',':
                res+=cur
                cur=['']
        return sorted(set(res+cur))

class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        stack = []
        for letter in expression:
            if letter.isalpha():
                stack.append(set(letter))
            elif letter == '{':
                stack.append('{')
            elif letter == ',':
                stack.append(',')
            elif letter == '}': #Only deal with problems here
                #Stack[-1] must be a set otherwise violates sense
                while stack[-2] == ',':
                    set2 = stack.pop()
                    stack.pop()
                    stack[-1].update(set2)
                #Stack[-2] must be '{' now
                tail = stack.pop()
                stack[-1] = tail 
            while len(stack) > 1 and isinstance(stack[-1], set) and isinstance(stack[-2], set):
                set2 = stack.pop()
                set1 = stack.pop()
                stack.append(set(w1 + w2 for w1 in set1 for w2 in set2))
            
        return list(sorted(stack[-1]))

import itertools

class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:          
        expression = \"{{{0}}}\".format(expression)
        s = []
        exp = ''        
        for x in (expression):
            if x in ('{', ',', '}'):
                if exp:
                    s.append([exp])
                    exp = ''
                
                while len(s) > 2 and s[-1] not in ('{', ',', '}') and s[-2] not in ('{', ',', '}'):
                    w2, w1 = s.pop(), s.pop()
                    s.append(sorted([''.join(y) for y in itertools.product(w1,w2)]))                                                                     
                
                if x == \"}\":
                    words = set()
                    w = s.pop()                        
                    while w != '{':
                        if w != \",\":                          
                            words.update(w)
                            
                        w = s.pop()
                        
                    s.append(sorted(words))
                else:
                    s.append(x)  
                    
            else:
                if exp == '':
                    exp = x
                else:
                    exp += x
                    
        return s[0]


class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        stack, cur, prev = [], [], []
        for c in expression:
            if c.isalpha():
                cur = [x + c for x in cur or [\"\"]]
            elif c == ',':
                # Attach cur to prev
                prev += cur
                cur = []
            elif c == '{':
                #print(\"{\", stack, cur, prev)
                stack.append(cur)
                stack.append(prev)
                cur, prev = [], []
            else:
                # Attach cur to prev
                prev += cur
                pre_prev = stack.pop()
                pre_cur = stack.pop()
                # multiply prev and pre_cur
                cur= [p+c for c in prev for p in pre_cur or ['']]
                prev = pre_prev
                #print(\"}\", stack, cur, prev)
        return sorted(set(cur+prev))


class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        # print(expression, len(expression))
        def helper(words1, words2):
            # print(words1, words2)
            s = set([])
            for word in words1:
                s.update([word + w for w in words2])
            return list(s)
        
        if len(expression) == 1:
            return [expression]
        n = len(expression)
        b = False
        if expression[0] == '{':
            cnt = 0
            i = 0
            while i < n:
                if expression[i] == '{':
                    cnt += 1
                elif expression[i] == '}':
                    cnt -= 1
                    if not cnt:
                        break
                i += 1
            if i == n - 1:
                b = True
        if b:
            res = set([])
            cnt = 0
            i0 = i = 1
            while i < n - 1:
                if expression[i] == '{':
                    cnt += 1
                elif expression[i] == '}':
                    cnt -= 1
                elif expression[i] == ',' and cnt == 0:
                    ret = self.braceExpansionII(expression[i0:i])
                    res.update(ret)
                    i0 = i + 1
                i += 1
            ret = self.braceExpansionII(expression[i0:i])
            res.update(ret)
            return sorted(list(res))
        else:
            res = [\"\"]
            i0 = i = 0
            while i < n:
                while i < n and not expression[i] == '{':
                    i += 1
                res = helper(res, [expression[i0:i]])
                i0 = i
                cnt = 0
                while i < n:
                    # print(i, expression[i], cnt)
                    if expression[i] == '{':
                        cnt += 1
                    elif expression[i] == '}':
                        cnt -= 1
                        if not cnt:
                            ret = self.braceExpansionII(expression[i0:(i+1)])
                            res = helper(res, ret)
                            i0 = i + 1
                            break
                    i += 1
            return sorted(list(set(res)))
                
                     

class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        groups = [[]]
        level = 0
        for i, c in enumerate(expression):
            if c == '{':
                if level == 0:
                    start = i+1
                level += 1
            elif c == '}':
                level -= 1
                if level == 0:
                    groups[-1].append(self.braceExpansionII(expression[start:i]))
            elif c == ',' and level == 0:
                groups.append([])
            elif level == 0:
                groups[-1].append([c])
        word_set = set()
        for group in groups:
            word_set |= set(map(''.join, itertools.product(*group)))
        return sorted(word_set)


class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        
        res = set()
        queue = []
        queue.append(expression)
        seen = set()
        while queue:
            n = len(queue)
            
            for i in range(n):
                exp = queue.pop(0)
                
                if exp in seen:
                    continue
                else:
                    seen.add(exp)
                
                if exp.find(\"{\") == -1:
                    res.add(exp)
                    continue
                    
                for j in range(len(exp)):
                    if exp[j] == \"}\":
                        right = j
                        break
                    
                    if exp[j] == \"{\":
                        left = j
                
                arr = exp[left+1:right].split(\",\")
                
                for element in arr:
                    queue.append(exp[:left] + element + exp[right+1:])
                
        return sorted(list(res))
        

import itertools

from abc import ABC, abstractmethod

class Syntax(ABC):
    def __init__(self, next=None):
        self.next = next
    
    @abstractmethod
    def get_values(self):
        return []
    
    def get_strings(self):
        if self.next is None:
            return self.get_values()
        
        return (a+b for a in self.get_values() for b in self.next.get_strings())
    
class Letter(Syntax):
    def __init__(self, letter, next=None):
        super().__init__(next)
        self.letter = letter
        
    def get_values(self):
        return [self.letter]
    
class Union(Syntax):
    def __init__(self, elts, next=None):
        super().__init__(next)
        self.elts = elts
        
    def get_values(self):
        return itertools.chain(*[elt.get_strings() for elt in self.elts])
    
class Solution:
    def find_close_brace(self, expression, offset):
        level = 1
        
        while level:
            offset += 1
            if expression[offset] == '{':
                level += 1
            elif expression[offset] == '}':
                level -= 1
        
        return offset
    
    def split_union_commas(self, expression):
        left = 0
        curr = 0
        
        expressions = []
        
        while left < len(expression):
            if expression[curr] == '{':
                curr = self.find_close_brace(expression, curr) + 1
            elif expression[curr] == ',':
                expressions.append(expression[left:curr])
                curr += 1
                left = curr
            else:
                curr += 1
                
            if curr == len(expression):
                expressions.append(expression[left:curr])
                break
                
        return expressions
    
    def parse(self, expression, offset):
        if offset == len(expression):
            return None
        
        if expression[offset] != '{':
            # this is a letter
            try:
                word_end = expression.index('{', offset)
            except ValueError:
                word_end = len(expression)
                
            return Letter(expression[offset:word_end], self.parse(expression, word_end))
        
        # parse union
        close_idx = self.find_close_brace(expression, offset)
        return Union(self.parse_union(expression[offset+1:close_idx]), self.parse(expression, close_idx+1))
        
    def parse_union(self, expression):
        elts = self.split_union_commas(expression)
        return [self.parse(elt, 0) for elt in elts]
    
    def braceExpansionII(self, expression: str) -> List[str]:
        head = self.parse(expression, 0)
        if head is None:
            return []
        
        return sorted(list(set(head.get_strings())))