Generate Parentheses

Difficulty: Medium

Given a number n, generate every distinct arrangement of n pairs of parentheses that is validly matched: every opening bracket has a closing bracket, and they never close in the wrong order.

Examples

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

These are all 5 distinct ways to arrange 3 pairs of parentheses so that every opening bracket is properly matched and nested.

Input: n = 1
Output: ["()"]

Input: n = 2
Output: ["(())", "()()"]

Constraints

  • 1 <= n <= 8

Approach

You could generate every sequence of 2n brackets and keep the valid ones. But most sequences are invalid, so most of the work is wasted.

Instead, use backtracking to build only sequences that could still be valid. Track how many opening and closing brackets you've placed:

  • Add an opening bracket if you've used fewer than n.
  • Add a closing bracket only if there are more opening brackets than closing ones. Otherwise you'd close something never opened.

Once the string reaches length 2n, it's guaranteed to be valid.

Solutions

Brute Force — Generate All, Then Filter

Build every sequence of length 2n from '(' and ')', then keep only the valid ones.

function generateParenthesis(n) {
  const result = [];
  const total = 2 * n;

  function isValid(str) {
    let balance = 0;
    for (const char of str) {
      balance += char === "(" ? 1 : -1;
      if (balance < 0) return false;
    }
    return balance === 0;
  }

  function build(current) {
    if (current.length === total) {
      if (isValid(current)) result.push(current);
      return;
    }
    build(current + "(");
    build(current + ")");
  }

  build("");
  return result;
}

Time: O(2^(2n) * n) — every one of the 2^(2n) sequences is generated, and each is validated in O(n) · Space: O(n) recursion depth, plus the space to store the output

Optimal — Backtracking (Only Build Valid Prefixes)

Build the string one character at a time. Add an opening bracket only if fewer than n are used, and a closing bracket only if it won't outnumber the opening ones. Every complete string is valid.

function generateParenthesis(n) {
  const result = [];

  function backtrack(current, openCount, closeCount) {
    if (current.length === 2 * n) {
      result.push(current);
      return;
    }
    if (openCount < n) {
      backtrack(current + "(", openCount + 1, closeCount);
    }
    if (closeCount < openCount) {
      backtrack(current + ")", openCount, closeCount + 1);
    }
  }

  backtrack("", 0, 0);
  return result;
}

Time: O(4^n / sqrt(n)) — the number of valid combinations (the nth Catalan number), each built in O(n) · Space: O(n) recursion depth, plus the space to store the output