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
Coding & Algorithms
Software Engineer
OpenAI
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

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
recursive descent parsing
backtracking
cartesian product
grammars
deduplication
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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...


Submit Your Answer
Markdown supported