Browse Curriculum
FAANGPrep Sprint
Medium

Generate Parentheses

Generate all combinations of well-formed parentheses.

Problem Understanding

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

Example: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Algorithm Strategy

Instead of generating all $2^{2n}$ strings and validating them, we can build only valid strings.

Rules:

  1. Open: We can add an open parenthesis ( if open_count < n.
  2. Close: We can add a closing parenthesis ) if closed_count < open_count.

This ensures we never close more than we open (validity) and never exceed n (completeness).

Interactive Visualization

Step 1 / 1
Empty Heap

Initializing...

1x

Visualize the decision choices between '(' and ')'. Red paths would violate validity constraints and are pruned.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.