FastPrepGenerate Parentheses
Problem · String

Generate Parentheses

Learn this problem
MediumAmazon logoAmazonNEW GRADONSITE INTERVIEW
See Amazon hiring insights

Problem statement

Given n pairs of parentheses, return every well-formed sequence containing exactly those pairs.

Return the sequences in lexicographic order.

Function

generateParenthesis(n: int) → String[]

Examples

Example 1

n = 3return = ["((()))","(()())","(())()","()(())","()()()"]

These are all five balanced sequences using three pairs, ordered lexicographically.

Example 2

n = 4return = ["(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"]

Covers Catalan growth, lexicographic order, and the smallest and larger bounded inputs.

Example 3

n = 1return = ["()"]

Covers Catalan growth, lexicographic order, and the smallest and larger bounded inputs.

Constraints

  • 1 <= n <= 8

More Amazon problems

drafts saved locally
public String[] generateParenthesis(int n) {
  // Write your code here.
}
n3
expected["((()))", "(()())", "(())()", "()(())", "()()()"]
checking account