Evaluate Nested Unions and Concatenations of Words
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Other
### Problem
Evaluate the valid expression as a set of lowercase words. A letter denotes its one-letter word. Braces containing a comma-separated list of two or more expressions denote set union. Adjacent expressions concatenate every word from the first set with every word from the second. Braces may nest. Return each resulting word once, in lexicographic order.
```cpp
class Solution {
public:
vector<string> braceExpansionII(string expression);
};
```
### Examples
**Example 1:**
```text
Input: expression = "{x,y}{a,{b,c}}"
Output: ["xa","xb","xc","ya","yb","yc"]
Explanation: The second factor denotes a,b,c and combines with each first-factor letter.
```
**Example 2:**
```text
Input: expression = "{{a,b},a{b,c},ab}"
Output: ["a","ab","ac","b"]
Explanation: The word ab arises twice but appears once in the sorted set.
```
### Constraints
- The expression length is between 1 and 60.
- Characters are lowercase English letters, `{`, `}` or `,`.
- The expression is valid under the stated grammar.
### Contract considerations
This grammar allows nested expressions, unlike independent nonnested character-option groups.
```hint Read the boundary condition
If two alternatives produce the same word, should it appear more than once in the returned list?
```
### Boundary reminders
This grammar allows nested expressions, unlike independent nonnested character-option groups.
Overview: Evaluate Nested Unions and Concatenations of Words. Evaluate the valid expression as a set of lowercase words.
Evaluate Nested Unions and Concatenations of Words
Google
Source window: 0–3 months · as of Oct 21, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0
Problem
Evaluate the valid expression as a set of lowercase words. A letter denotes its one-letter word. Braces containing a comma-separated list of two or more expressions denote set union. Adjacent expressions concatenate every word from the first set with every word from the second. Braces may nest. Return each resulting word once, in lexicographic order.
class Solution {
public:
vector<string> braceExpansionII(string expression);
};
Examples
Example 1:
Input: expression = "{x,y}{a,{b,c}}"
Output: ["xa","xb","xc","ya","yb","yc"]
Explanation: The second factor denotes a,b,c and combines with each first-factor letter.
Example 2:
Input: expression = "{{a,b},a{b,c},ab}"
Output: ["a","ab","ac","b"]
Explanation: The word ab arises twice but appears once in the sorted set.
Constraints
The expression length is between 1 and 60.
Characters are lowercase English letters,
{
,
}
or
,
.
The expression is valid under the stated grammar.
Contract considerations
This grammar allows nested expressions, unlike independent nonnested character-option groups.
Boundary reminders
This grammar allows nested expressions, unlike independent nonnested character-option groups.