MediumBacktrackingRecursionString

Generate Parentheses

LeetCode
1 approach, code in all languages

You are given a whole number n that represents how many pairs of round brackets are available. Your job is to produce every distinct arrangement of these brackets that is properly balanced, meaning each opening bracket is eventually closed and no closing bracket ever appears before a matching opening one.

Return the collection of all such well-formed strings. The relative ordering of the results is not important, but each valid arrangement must appear exactly once.

Example 1

Input: n = 2

Output: ["(())", "()()"]

With two pairs there are exactly two balanced layouts: a nested pair and two side-by-side pairs.

Example 2

Input: n = 1

Output: ["()"]

A single pair can only be written one way.

Constraints

  • 1 <= n <= 8
  • Every returned string has length exactly 2 * n
  • The count of valid results equals the nth Catalan number
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now