Skip to content
StackDecode
BacktrackingAnimated

Generate Parentheses

Add "(" while fewer than n are used, and ")" while it would stay balanced.

Time

O(4ⁿ / √n)

Extra space

O(n)

Use it for

All valid bracket strings.

How it works

  1. Build the string one character at a time.
  2. You may add "(" while fewer than n have been used.
  3. You may add ")" only while there are more "(" than ")" so far. This rule is the pruning: it never lets the string become invalid.
  4. When the string has length 2n, record it. Backtrack to explore the other choices. The count is the Catalan number.

Watch it run

Loading animation…