Generate Every Valid Nesting Layout for N Packing Boxes
Last updated: November 29, 2026
Quick Overview
Represent placing a box as `(` and closing it as `)`. Given n boxes, return every string of n opening and n closing marks that forms a valid nesting.
Amazon
November 29, 20260
0
0 solved
Represent placing a box as `(` and closing it as `)`. Given n boxes, return every string of n opening and n closing marks that forms a valid nesting.
An online assessment style backtracking question in Amazon's style. It checks whether you prune with open and close counts during generation instead of generating all 2^(2n) strings and filtering.
What the Interviewer Expects
- Builds strings character by character with counts
- Adds ( only while open < n
- Adds ) only while close < open
- Explains that pruning yields only valid strings
- Mentions the Catalan number output size
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
- How would you return the k-th layout in lexicographic order without generating all of them?
- How would you support two kinds of boxes, ( ) and [ ]?
- How would you count layouts for n = 1000 modulo a prime?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Return all balanced strings of length . Order is not required, but this approach naturally produces lexicographic order because ( sorts before ) and is tried first....
High-Level Design
A prefix can be extended to a valid string iff closed <= opened <= n. So at each step: add ( if fewer than n are open, add ) if it would not close more than were opened. Every leaf of this sea...