Magicsheet logo

Generate Parentheses

Medium
56.3%
Updated 6/1/2025

Generate Parentheses

What is this problem about?

In the Generate Parentheses coding problem, you are given an integer nn. You need to generate all possible combinations of well-formed parentheses strings using nn pairs of brackets. For example, if n=2n=2, the valid strings are "(())" and "()()".

Why is this asked in interviews?

This is one of the most frequent technical interview questions, asked by Meta, Amazon, and Uber. it's a perfect test of Backtracking and recursive thinking. It evaluation whether you understand the rules of "well-formedness" (balance): you can never add more closing brackets than opening ones, and you can only use nn of each. It tests your ability to visualize a decision tree and handle state constraints.

Algorithmic pattern used

This is a Backtracking problem.

  1. Maintain two counters: openCount and closeCount.
  2. Recursive function backtrack(currentString):
    • If openCount < n, you can add a '('.
    • If closeCount < openCount, you can add a ')'.
    • Base Case: If currentString.length == 2 * n, add the string to your result. By following these rules, the recursion only explores valid paths, ensuring every generated string is well-formed.

Example explanation

n=2n = 2

  1. Start: "". open=0, close=0.
  2. Add '(': "(". open=1, close=0.
  3. Next level:
    • Add '(': "((". open=2, close=0. (Now open is at limit).
    • Add ')': "()". open=1, close=1.
  4. From "((": can only add ')'. Result: "(())".
  5. From "()": can only add '('. Result: "()(" o o "()()".

Common mistakes candidates make

  • Validation after generation: Generating all 22n2^{2n} combinations and then checking if they are balanced. This is O(22nimesn)O(2^{2n} imes n) and extremely slow compared to the backtracking approach.
  • Wrong conditions: Letting closeCount exceed openCount or openCount exceed nn.
  • String mutation: Forgetting how string concatenation works in recursive calls (though in most languages, passing strings by value handles this automatically).

Interview preparation tip

Practice the Backtracking interview pattern. This problem is the "Hello World" of backtracking. Once you master it, you can solve similar problems like "Letter Combinations of a Phone Number" or "N-Queens."

Similar Questions