Generate Parentheses

MediumBacktrackingbacktracking

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer n representing the number of pairs of parentheses, return **every** distinct string that can be formed using exactly n pairs of well-formed parentheses. A string of parentheses is **well-formed** when: - It uses exactly n opening characters '(' and n closing characters ')'. - At no point while scanning the string from left to right does the count of ')' exceed the count of '('. - Every opening parenthesis is eventually matched by a closing parenthesis. For example, with n = 2 the strings "(())" and "()()" are valid, but ")(" and "()(" are not. You may return the strings in **any order**. When n = 0, the only well-formed result is the empty string "".

Examples

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
All five distinct arrangements of 3 pairs of balanced parentheses.
Input: n = 1
Output: ["()"]
A single pair has exactly one valid form.
Input: n = 0
Output: [""]
With zero pairs the only well-formed string is the empty string.

Constraints

  • 0 <= n <= 8
  • The number of valid strings equals the n-th Catalan number, so the output stays small for the given bound.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More backtracking problems