Expand Nested Prompt Templates Into All Unique Variants
Last updated: November 29, 2026
Quick Overview
Given a template with nestable alternative groups like `Tell me {a joke,a story} about {cats,dogs}`, return every distinct expansion in sorted order, where braces offer comma-separated options and adjacent parts concatenate.
OpenAI
November 29, 20260
0
0 solved
Given a template with nestable alternative groups like `Tell me {a joke,a story} about {cats,dogs}`, return every distinct expansion in sorted order, where braces offer comma-separated options and adjacent parts concatenate.
Evaluation and red-teaming work at OpenAI often generates prompt variants from templates, so a brace-expansion grammar is a realistic coding exercise. Interviewers check whether you write a real recursive descent parser instead of fragile string splitting, handle nesting and empty options, and deduplicate correctly.
What the Interviewer Expects
- State a grammar with alternatives and sequences before coding
- Implement recursive descent with a shared cursor
- Combine sequence parts by cartesian product and alternatives by set union
- Support nesting and empty options like `{b,}`
- Report malformed templates instead of silently producing output
- Discuss output size blowup
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Output can be exponential: how would you stream expansions lazily instead of building sets?
- Add escaping so a literal comma or brace can appear.
- Return a uniformly random expansion without enumerating all of them.
- Count the expansions without generating them; what about duplicates?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Grammar:
alternatives := sequence (',' sequence)*,sequence := (literal | '{' alternatives '}')*. - A top-level comma also separates alternatives, mirroring the inner rule.
- Output: sorted uniq...
High-Level Design
Use one cursor over the template and two mutually recursive functions. parse_sequence reads literals and brace groups until it hits a comma or a closing brace, combining pieces with a cartesian prod...