InterviewPrepKit

Home / Coding / Stack

Generate Parentheses

medium Original β†—
Solving tips
  • Don't generate all 2^(2n) strings and filter; use backtracking that only ever extends valid prefixes so every leaf is an answer.
  • The single invariant: add '(' while opens < n, and add ')' only while closes < opens (not closes < n, which would produce ')(').
  • With a shared mutable path buffer, remember to pop() after each recursive call to undo; no set-based dedup is needed since each string is produced once.
  • Know the complexity is the nth Catalan number, Theta(4^n / n^1.5), with O(n) extra space for the recursion depth; interviewers probe this.

Problem

Given an integer n, produce every distinct string of n opening and n closing parentheses that is well-formed β€” reading left to right, the count of ) never exceeds the count of (, and the counts are equal at the end. Return the strings in any order.

Examples

  • n = 1 β†’ ["()"] β€” only one balanced string of length 2.
  • n = 2 β†’ ["(())", "()()"] β€” nest or concatenate.
  • n = 3 β†’ ["((()))", "(()())", "(())()", "()(())", "()()()"] β€” the 5 balanced strings of length 6 (5 is the 3rd Catalan number).

Constraints

  • 1 <= n <= 8

The output itself is exponential (Catalan-number many strings, ~1430 for n = 8), so the goal is to generate only valid strings β€” never enumerate all 2^(2n) candidates and filter.

Think about it first

Hint 1 Build the string one character at a time. At any moment, when are you still *allowed* to add a `(`? When may you add a `)`?
Hint 2 Track two counters: opens used and closes used. You can add `(` while `opens < n`, and `)` only while `closes < opens` β€” that single inequality is exactly what keeps every prefix valid.
Hint 3 Recurse on both legal choices, appending to a shared buffer and undoing the append on the way back up (backtracking). Every leaf at length `2n` is a valid answer β€” no filtering needed, and the recursion never explores a dead branch.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.