#22

Generate Parentheses

Medium Backtracking with counts

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return every valid string of n pairs of parentheses.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: all valid strings with n pairs of brackets.

Why this works: add '(' while you have some left; add ')' only if it closes something open. Only valid strings get built.

Example: n = 2

"((" → "(())""()" → "()()"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Generating all 2^(2n) strings and filtering valid ones.

Solve on LeetCode ↗
Complexity
  • Time: O(4^n / √n) — the Catalan number of results.
  • Space: O(n).
Topic: Recursion & Backtracking
🎬 Episodes 29–36: video coming soon