#22

Generate Parentheses

MediumBacktrackingHas vizStringBacktracking

Problem

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1

Input: n = 3

Output: ["((()))","(()())","(())()","()(())","()()()"]

All valid sequences with 3 pairs.

Example 2

Input: n = 1

Output: ["()"]

Only one valid string.

Constraints

  • 1 <= n <= 8
Loading visualization…

Explanation

Generate Parentheses is a Medium interview problem tagged [String, Backtracking]. The winning approach is typically **Backtracking**.

Intuition

Systematically covers the decision tree with pruning.

Approach

Build a partial solution; recurse; undo (pop) after exploring.

  1. Choose.
  2. Explore.
  3. Unchoose.
  4. Prune invalid partials early.
  5. Copy path when saving answers.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateBacktracking

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(2^n) – O(n!)

Space: O(n)

Before coding, restate the problem, name the pattern (Backtracking), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #22 Generate Parentheses as understood when the pattern clicks.