Generate All Valid Combinations of Balanced Parentheses
Company: Disney
Role: Data Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question tests a candidate's ability to apply recursive backtracking and combinatorial generation in a coding interview context. It evaluates understanding of constraint-based enumeration and string construction, core algorithmic skills frequently assessed in software engineering and data engineering roles.
Constraints
- 0 <= n <= 8
- Every string in the output uses exactly n opening and n closing parentheses.
- All strings in the output must be distinct and well-formed.
- For n = 0 the output is a list containing the single empty string: [""].
Examples
Input: (3,)
Expected Output: ['((()))', '(()())', '(())()', '()(())', '()()()']
Explanation: n = 3: there are Catalan(3) = 5 well-formed strings, shown in lexicographic order.
Input: (1,)
Expected Output: ['()']
Explanation: n = 1: the only balanced string is '()'.
Input: (0,)
Expected Output: ['']
Explanation: Boundary: n = 0 yields exactly one string, the empty string.
Input: (2,)
Expected Output: ['(())', '()()']
Explanation: n = 2: Catalan(2) = 2 valid strings.
Input: (4,)
Expected Output: ['(((())))', '((()()))', '((())())', '((()))()', '(()(()))', '(()()())', '(()())()', '(())(())', '(())()()', '()((()))', '()(()())', '()(())()', '()()(())', '()()()()']
Explanation: n = 4: Catalan(4) = 14 valid strings, sorted lexicographically.
Hints
- Build strings character by character with backtracking. Track how many '(' and ')' you have placed so far.
- You may add a '(' as long as you have used fewer than n opening brackets. You may add a ')' only when the count of ')' placed is strictly less than the count of '(' placed — this keeps every prefix valid.
- Stop and record the string once its length reaches 2n. Return the collected strings sorted so the output ordering is deterministic.