CodeSpeek

Generate Parentheses

Medium · Stack

You are given a single integer n. Build every valid string of length 2n that uses exactly n opening parentheses and n closing parentheses so that at no point in the string do the closing parentheses outnumber the opening ones read so far. Return all such well-formed combinations, in any order.

Examples

Input:  n = 1
Output: ["()"]
Why:    With one pair, the only balanced arrangement is ().
Input:  n = 2
Output: ["(())", "()()"]
Why:    These are the only two ways to nest or sequence two pairs of parentheses without ever closing more than has been opened.
Input:  n = 3
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
Why:    All five balanced arrangements of three parenthesis pairs, listed here as an unordered set.

Constraints

1 <= n <= 8

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Generate Parentheses

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Generate Parentheses. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.