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 - Queue-Based BFS INPUT s = "a{b,c}" a fixed {b,c} options Parsed Structure: ["a"] ["b"] ["c"] Input String: "a{b,c}" ALGORITHM STEPS 1 Initialize Queue Queue = [""] (empty string) "" 2 Process 'a' Append 'a' to all in queue "a" 3 Process {b,c} Branch for each option "ab" "ac" 4 Sort Results Lexicographic order BFS explores level by level Final Queue State: ["ab", "ac"] FINAL RESULT All possible words: "ab" "ac" Sorted: a-b before a-c (lexicographic order) Output Array: ["ab", "ac"] OK - 2 words found Key Insight: BFS with a queue processes the string character by character. For each position with multiple options (inside braces), we multiply the current queue size by creating new combinations. Time Complexity: O(n * k^m) where n=length, k=max options, m=number of brace groups. TutorialsPoint - Brace Expansion | Queue-Based BFS Approach
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