1096. Brace Expansion II LeetCode Solution

In this guide, you will get 1096. Brace Expansion II LeetCode Solution with the best time and space complexity. The solution to Brace Expansion II problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Brace Expansion II solution in C++
  4. Brace Expansion II solution in Java
  5. Brace Expansion II solution in Python
  6. Additional Resources
1096. Brace Expansion II LeetCode Solution image

Problem Statement of Brace Expansion II

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.

See also  145. Binary Tree Postorder Traversal LeetCode Solution

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 <= 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.

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

1096. Brace Expansion II LeetCode Solution in C++

class Solution {
 public:
  vector<string> braceExpansionII(string expression) {
    return dfs(expression, 0, expression.length() - 1);
  }

 private:
  vector<string> dfs(const string& expression, int s, int e) {
    set<string> ans;
    vector<vector<string>> groups{{}};
    int layer = 0;
    int left = 0;

    for (int i = s; i <= e; ++i)
      if (expression[i] == '{' && ++layer == 1)
        left = i + 1;
      else if (expression[i] == '}' && --layer == 0)
        merge(groups, dfs(expression, left, i - 1));
      else if (expression[i] == ',' && layer == 0)
        groups.push_back({});
      else if (layer == 0)
        merge(groups, {string(1, expression[i])});

    for (const vector<string>& group : groups)
      for (const string& word : group)
        ans.insert(word);

    return {ans.begin(), ans.end()};
  }

  void merge(vector<vector<string>>& groups, const vector<string> group) {
    if (groups.back().empty()) {
      groups[groups.size() - 1] = group;
      return;
    }

    vector<string> mergedGroup;

    for (auto& word1 : groups.back())
      for (auto& word2 : group)
        mergedGroup.push_back(word1 + word2);

    groups[groups.size() - 1] = mergedGroup;
  }
};
/* code provided by PROGIEZ */

1096. Brace Expansion II LeetCode Solution in Java

class Solution {
  public List<String> braceExpansionII(String expression) {
    return dfs(expression, 0, expression.length() - 1);
  }

  private List<String> dfs(final String expression, int s, int e) {
    TreeSet<String> ans = new TreeSet<>();
    List<List<String>> groups = new ArrayList<>();
    groups.add(new ArrayList<>());
    int layer = 0;
    int left = 0;

    for (int i = s; i <= e; ++i)
      if (expression.charAt(i) == '{' && ++layer == 1)
        left = i + 1;
      else if (expression.charAt(i) == '}' && --layer == 0)
        merge(groups, dfs(expression, left, i - 1));
      else if (expression.charAt(i) == ',' && layer == 0)
        groups.add(new ArrayList<>());
      else if (layer == 0)
        merge(groups, new ArrayList<>(List.of(String.valueOf(expression.charAt(i)))));

    for (final List<String> group : groups)
      for (final String word : group)
        ans.add(word);

    return new ArrayList<>(ans);
  }

  void merge(List<List<String>> groups, List<String> group) {
    if (groups.get(groups.size() - 1).isEmpty()) {
      groups.set(groups.size() - 1, group);
      return;
    }

    List<String> mergedGroup = new ArrayList<>();

    for (final String word1 : groups.get(groups.size() - 1))
      for (final String word2 : group)
        mergedGroup.add(word1 + word2);

    groups.set(groups.size() - 1, mergedGroup);
  }
}
// code provided by PROGIEZ

1096. Brace Expansion II LeetCode Solution in Python

class Solution:
  def braceExpansionII(self, expression: str) -> list[str]:
    def merge(groups: list[list[str]], group: list[str]) -> None:
      if not groups[-1]:
        groups[-1] = group
        return

      groups[-1] = [word1 + word2 for word1 in groups[-1]
                    for word2 in group]

    def dfs(s: int, e: int) -> list[str]:
      groups = [[]]
      layer = 0

      for i in range(s, e + 1):
        c = expression[i]
        if c == '{':
          layer += 1
          if layer == 1:
            left = i + 1
        elif c == '}':
          layer -= 1
          if layer == 0:
            group = dfs(left, i - 1)
            merge(groups, group)
        elif c == ',' and layer == 0:
          groups.append([])
        elif layer == 0:
          merge(groups, [c])

      return sorted(list({word for group in groups for word in group}))

    return dfs(0, len(expression) - 1)
# code by PROGIEZ

Additional Resources

See also  913. Cat and Mouse LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.