Given a positive number n, find all strings of length n containing balanced parentheses.

For example,

Input:  n = 4
Output:
(())
()()
 
Input:  n = 6
Output:
((()))
(()())
(())()
()(())
()()()
 
Input:  n = 5
Output: Invalid input

Practice this problem

We can use recursion to solve this problem. The idea is to maintain a count of the open parenthesis in the output string. Then

  • Recur with open parentheses with one less character and an increased count of open parentheses.
  • Recur with closed parentheses only if the output string has at least one open parenthesis. And recur with one less character and a decreased count of open parentheses.

If the desired length n is reached and the output string contains all balanced parenthesis, print it. Return if we cannot close all open parentheses with left characters. Also, if the total number of characters is odd and there are no open parentheses, we cannot form the balanced parentheses.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

((()))
(()())
(())()
()(())
()()()

Java


Download  Run Code

Output:

((()))
(()())
(())()
()(())
()()()

Python


Download  Run Code

Output:

{‘()(())’, ‘()()()’, ‘(())()’, ‘(()())’, ‘((()))’}

The time complexity of the above solution is exponential as there are exactly 2n-1 combinations, where n is the length of the input string. It also requires additional space for the recursion (call stack).