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.

Input & Output

Example 1 — Basic Expansion
$ Input: s = "a{b,c}"
Output: ["ab","ac"]
💡 Note: The first character is 'a', the second can be 'b' or 'c', giving us "ab" and "ac". Results are sorted lexicographically.
Example 2 — Multiple Options
$ Input: s = "{a,b}{c,d}"
Output: ["ac","ad","bc","bd"]
💡 Note: First position has options {a,b}, second has {c,d}. All combinations: ac, ad, bc, bd. Already in lexicographical order.
Example 3 — Mixed Fixed and Variable
$ Input: s = "a{b,c}d{e,f}"
Output: ["abde","abdf","acde","acdf"]
💡 Note: Fixed 'a', options {b,c}, fixed 'd', options {e,f}. Generate all 4 combinations and sort.

Constraints

  • 1 ≤ s.length ≤ 50
  • s consists of lowercase English letters, '{', '}', and ','
  • All the values in s are unique

Visualization

Tap to expand
Brace Expansion Overview"a{b,c}d"Input String"a""{b,c}""d"Parsed"abd""acd"All Combinations["abd", "acd"]
Understanding the Visualization
1
Input
String with braces indicating character options
2
Parse
Identify fixed characters and option groups
3
Expand
Generate all combinations systematically
4
Sort
Return results in lexicographical order
Key Takeaway
🎯 Key Insight: Parse options first, then systematically expand combinations level by level
Asked in
Google 25 Facebook 20 Amazon 15
32.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen