</>

22. Generate Parentheses

Medium NeetCode 150
Stack Time O(4^N / sqrt(N) Space O(N)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Stack
Time
O(4^N / sqrt(N)
Space
O(N)

Standard Solution (C++)

SummaryGiven an integer n, produce every possible string of n opening and n closing parentheses that forms a valid (properly nested) sequence.

Approach
  • Use recursive backtracking, tracking how many ( and ) have been placed so far.
  • At each step, add ( if the open count is still below n, and add ) only when the close count is strictly less than the open count — this invariant guarantees validity at every prefix.
  • When the current string reaches length 2n, it is a complete valid combination and is recorded.
  • Because the constraint prunes invalid branches immediately, no post-generation filtering is needed; the number of valid results equals the n-th Catalan number.
#include <string>
#include <vector>
using namespace std;

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        dfs(result, "", 0, 0, n);
        return result;
    }

private:
    // open  = '(' placed so far
    // close = ')' placed so far
    void dfs(vector<string>& result, string cur, int open, int close, int n) {
        if ((int)cur.size() == 2 * n) {
            result.push_back(cur);
            return;
        }
        // Can add '(' as long as we have quota remaining
        if (open < n)
            dfs(result, cur + '(', open + 1, close, n);
        // Can add ')' only when it won't exceed open count (keeps prefix valid)
        if (close < open)
            dfs(result, cur + ')', open, close + 1, n);
    }
};
Time O(4^n / sqrt(n)) — the number of valid combinations equals the n-th Catalan number, and each string has length 2n Space O(n) auxiliary stack depth; O(4^n / sqrt(n)) for the output

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        backtrack(result, "", n, 0, 0);

        return result;
    }

    void backtrack(vector<string>& result, string current, int n, int leftNum, int rightNum){
        if(current.length()==2*n){
            result.push_back(current);
            return;
        }

        if(leftNum<n){
            current.push_back('(');
            backtrack(result, current, n, leftNum+1, rightNum);
            current.pop_back();
        }
        
        if(rightNum<leftNum){
            current.push_back(')');
            backtrack(result, current, n, leftNum, rightNum+1);
            current.pop_back();
        }

        return;
    }
};

// Time Complexity: O(4^N / sqrt(N)), or O(n*C_n) where C_n is the n-th Catalan number.
// Space Complexity: O(N) for auxiliary space, O(4^N / sqrt(N)) for the result.
Time O(4^N / sqrt(N) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern