Problem · String

Generate Balanced Parentheses

Learn this problem
MediumInMobi logoInMobiNEW GRADOA

Problem statement

Given an integer n, return every well-formed string that can be made with exactly n pairs of parentheses.

A string is well-formed when each opening parenthesis ( is matched with a later closing parenthesis ), and no prefix contains more closing parentheses than opening parentheses.

For deterministic judging, return the strings in ascending lexicographic order. Under the ordinary character ordering, ( comes before ).

Function

generateBalancedParentheses(n: int) → List<String>

Examples

Example 1

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

These are all five well-formed strings containing exactly three opening and three closing parentheses, listed in lexicographic order.

Example 2

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

The two well-formed strings with two pairs are (()) and ()(), in lexicographic order.

Example 3

n = 1return = ["()"]

Only one well-formed string can be made with one pair of parentheses.

Constraints

  • 1 ≤ n ≤ 10
  • The returned list must be in ascending lexicographic order.

More InMobi problems

drafts saved locally
public List<String> generateBalancedParentheses(int n) {
  // write your code here
}
n3
expected["((()))","(()())","(())()","()(())","()()()"]
checking account