InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Generate Parentheses

medium Original ↗ 00:00

Problem

Given an integer n, produce every distinct string of n opening and n closing parentheses that is well-formed — reading left to right, the count of ) never exceeds the count of (, and the counts are equal at the end. Return the strings in any order.

Examples

  • n = 1["()"] — only one balanced string of length 2.
  • n = 2["(())", "()()"] — nest or concatenate.
  • n = 3["((()))", "(()())", "(())()", "()(())", "()()()"] — the 5 balanced strings of length 6 (5 is the 3rd Catalan number).

Constraints

  • 1 <= n <= 8

The output is exponential (Catalan-number many strings, ~1430 for n = 8), so the goal is to generate only valid strings, not to enumerate all 2^(2n) candidates and filter.

Think about it first

Hint 1 Build the string one character at a time. When are you allowed to add a `(`? When may you add a `)`?
Hint 2 Track two counters: opens used and closes used. You can add `(` while `opens < n`, and `)` only while `closes < opens`. That single inequality keeps every prefix valid.
Hint 3 Recurse on both legal choices, appending to a shared buffer and undoing the append on the way back up (backtracking). Every leaf at length `2n` is a valid answer, with no filtering and no dead branches.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug