Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Backtracking High frequency Solution Available Practice Mode

Generate Parentheses LeetCode Solution

Tags: #String #Dynamic Programming #Backtracking

Approach Summary

Backtracking: add "(" if open < n; add ")" if close < open. Collect when len = 2n.

Practice Mode

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Backtracking Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Backtracking pattern.

Framework: Backtracking • Interview Prep: Tested at FAANG • Explore all Backtracking problems & invariants →

How to Recognize This Pattern

  • "All valid combinations of n pairs of parentheses"
  • Constraint: close ≤ open ≤ n at all times

Complexity Analysis

Time Complexity

O(4ⁿ / √n)

Space Complexity

O(n)

Tags

String Dynamic Programming Backtracking

Frequently Asked Questions

What is the optimal time and space complexity for Generate Parentheses?
The optimal solution for Generate Parentheses achieves O(4ⁿ / √n) runtime complexity and requires O(n) auxiliary space. The algorithm explores exactly the valid sequences, whose count is the n-th Catalan number C(n) = (1/(n+1))·C(2n, n) — O(C(n)) time. Each valid sequence is built and stored once; the recursion depth is at most 2n, giving O(n) space for the path plus the output.
How do I identify that Generate Parentheses requires the Backtracking pattern?
In technical interviews, look for key problem signals: "All valid combinations of n pairs of parentheses"; Constraint: close ≤ open ≤ n at all times. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Backtracking strategy.
What critical edge cases must be handled in Generate Parentheses?
Essential edge cases to verify include: n = 0 — the problem returns [""] (one empty string); n = 1 — exactly ["()"]; Unbalanced prefixes are never generated because close < open gates the closing branch; n = 3 — the five classic sequences: ((())), (()()), (())(), ()(()), ()()(). Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Generate Parentheses?
Generate Parentheses is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Google, Facebook, Microsoft.
Buy me a coffee
Daily Practice
0/0