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
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Online Assessment
Coding & Algorithms
Easy

0

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
backtracking
pruning
Catalan numbers
recursion
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
  • 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 Problems
Sample Answer
Requirements

Return all balanced strings of length 2n2n. 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...


Submit Your Answer
Markdown supported