MediumStringBacktrackingBreadth-First SearchUpdated Sep 2026

1087. Brace Expansion

Asked at Anduril

Difficulty

Medium

Time

O(L * P)

Space

O(L * P)

Pattern

String

Companies

1

Problem

You are given a pattern string s. It describes a set of words. A plain lowercase letter in s means that letter appears in every word. A group written as {a,b,c} means the word takes exactly one of those letters at that position.

For example, "a{b,c}" produces the words "ab" and "ac". The a is fixed, and the brace group offers two choices.

Return all words the pattern can produce, sorted in lexicographical order. There is no nesting: a brace group never sits inside another brace group.

One letter chosen from each group

pattern{a,b}c{d,e}f0123Positions 0 and 2 are choice groups; positions 1 and 3are fixed letters.outputacdfacefbcdfbcef0123All 2 × 1 × 2 × 1 = 4 words, listed in alphabeticalorder.
Each position contributes one letter, and a brace group lets you pick any of its options.

Constraints

  • ●1 <= s.length <= 50
  • ●s contains only curly brackets '{}', commas ',', and lowercase English letters
  • ●s is guaranteed to be a valid input
  • ●There are no nested curly brackets
  • ●All characters inside one pair of braces are different

Examples

Example 1
Inputs = "{a,b}c{d,e}f"
Output["acdf","acef","bcdf","bcef"]
WhyThe pattern has four positions: {a,b}, then c, then {d,e}, then f. Combining every choice gives acdf, acef, bcdf, bcef, and that list is already in alphabetical order.
Example 2
Inputs = "abcd"
Output["abcd"]
WhyThere are no braces, so every letter is fixed. Only one word can be formed.

Asked At

1 companies
CompanyDifficulty
AndurilMediumView all Anduril questions →

How to Think About It

1

Parse first: turn the string into a list of groups, where a plain letter is a group of size 1 and {x,y,z} is a group of three options.

2

The result is the Cartesian product of the groups. Build it with backtracking (choose one option per group) or iteratively (extend every partial word with each option).

3

Sort each group before expanding. Then backtracking generates words in lexicographic order automatically — no final sort needed.

4

Walkthrough for "{a,b}c{d,e}f": groups [a,b] [c] [d,e] [f] -> acdf, acef, bcdf, bcef.

5

The output can have up to the product of group sizes entries, so complexity is dominated by output size.

Optimal Approach

Step 1: Parse into groups: on {, read letters until } (skip commas) and sort them; otherwise the single letter is a group.
Step 2: res = [""].
Step 3: For each group, res = [w + c for w in res for c in group].
Step 4: Return res (already sorted because groups are sorted and processed in order).

Time: O(L * P) where P is the number of words and L their length. Space: O(L * P).

Parse, then extend word by word

parse into groups: [a,b] [c] [d,e] [f]sort each groupstart res = [""]Parsing turns the string into a list of option groups,each already sorted.res after group [a,b]abThe first group doubles the empty word into twopartial words.res after group [d,e]acdacebcdbceEach partial word branches into two, keeping the orderalphabetical.res = [w + c for w in res for c in group]sorted groups → sorted output
Start with one empty word and append every option of each group in turn.
ComplexityTime O(L * P)Space O(L * P)P is the number of output words and L is the length of each word; the cost is dominated by writing out every result word.

What Trips People Up in Real Interviews

1

Forgetting to sort the output. Sorting each group up front is the cheap way to get it for free.

2

Treating commas as characters in the result.

3

Using recursion with string slicing on the raw pattern at every step — parse once, then expand.

4

Assuming nested braces. This version has none; mention that Brace Expansion II handles nesting with a grammar.

Solution Code

O(L * P) time
def expand(s):
    groups = []
    i = 0
    while i < len(s):
        if s[i] == '{':
            j = s.index('}', i)
            groups.append(sorted(s[i + 1:j].split(',')))
            i = j + 1
        else:
            groups.append([s[i]])
            i += 1
    res = ['']
    for g in groups:
        res = [w + c for w in res for c in g]
    return res

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Brace Expansion problem?

Brace Expansion takes a pattern like `"{a,b}c{d,e}f"`, where each brace group lists alternative letters, and asks for every word it can produce, sorted lexicographically. There is no nesting, so parse the pattern into a list of option groups and take their Cartesian product.

How do you solve Brace Expansion?

The optimal approach runs in O(L * P) time and O(L * P) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Brace Expansion?

Brace Expansion is asked at Anduril. It is a medium difficulty problem.

What are common mistakes on Brace Expansion?
  • Forgetting to sort the output. Sorting each group up front is the cheap way to get it for free.
  • Treating commas as characters in the result.
  • Using recursion with string slicing on the raw pattern at every step — parse once, then expand.
  • Assuming nested braces. This version has none; mention that Brace Expansion II handles nesting with a grammar.