Generate ParenthesesLoading saved progress…

Generate Parentheses

A string of parentheses is well-formed when every ) closes a ( that came before it and nothing is left open — (()) and ()() are well-formed, but )( and (() are not. Given a number n, produce every well-formed string that uses exactly n pairs of parentheses. This is LeetCode 22; the number of answers for a given n is the Catalan number, which is why n = 3 has 5 results and the count climbs fast.

Signature

generateParentheses(n)  // integer n >= 0  ->  array of every well-formed string with n pairs

The order of the strings in the returned array is not specified — only the set of strings matters.

Examples

generateParentheses(1); // ['()']
generateParentheses(2); // ['(())', '()()']   (in any order)
generateParentheses(3);
// ['((()))', '(()())', '(())()', '()(())', '()()()']   (5 strings, any order)

Notes

  • Well-formed — scanning left to right, the number of ) never exceeds the number of (, and the two counts are equal at the end. (() and ()) are both malformed.
  • Order is not specified — return the strings in whatever order your algorithm produces; a grader compares the set, not the sequence.
  • n = 0 — there is exactly one well-formed string using zero pairs: the empty string. generateParentheses(0) returns [''], not [].
  • The count is a Catalan number — 1, 2, 5, 14, 42, … for n = 1, 2, 3, 4, 5. The result set grows roughly like 4^n, so keep n small.
  • Every string has length 2n and uses only the two characters ( and ). No duplicates appear in the output.

FAQ

How many well-formed strings are there for n pairs?
Exactly the nth Catalan number: 1, 2, 5, 14, 42 for n = 1, 2, 3, 4, 5. The closed form is C(2n, n) / (n + 1), and it grows roughly like 4^n, so the answer set gets large quickly even though each string is short.
Why does the backtracking never produce an invalid string?
Two guards enforce validity as the string is built: you add an open bracket only while open is below n, and a close bracket only while close is below open. Keeping close no greater than open at every step means every prefix is already a valid start, so no string is ever built that would have to be filtered out.
What is the time complexity?
Each of the Catalan(n) results costs O(n) to build, so the output-sensitive bound is O(n times Catalan(n)), close to O(4^n / sqrt(n)). The pruning is what keeps the work near the number of valid answers instead of the 2^(2n) brute-force space.
Loading editor…