Generate All Parentheses

Print all combinations of balanced parentheses problem

You are given a positive integer n, representing the number of pairs of parentheses. Your task is to generate and return all possible combinations of well-formed (valid) parentheses strings that can be created using exactly n pairs.

A well-formed parentheses string maintains the correct order, meaning every opening parenthesis ( has a corresponding closing parenthesis ) that appears after it.

Generate All Balanced Parentheses

Explanation: You may return the answer in any order.

Constraints:

  • 1 <= n <= 7

Print all combinations of balanced parentheses Solution

Recommendation for Time and Space Complexity –You should aim for a solution as good or better than O(4^n / sqrt(n)) time and O(n) space, where n is the number of parenthesis pairs in the string.

Hints for solving problems

Hint 1 :

A brute force solution would be to generate all possible strings of size 2n and add only the valid strings. This would be an O(n * 2 ^ (2n)) solution. Can you think of a better way? Maybe you can use pruning to avoid generating invalid strings.

Hint 2 :

We can use backtracking with pruning. But what makes a string invalid? Can you think of a condition for this?

Hint 3 :

When the count of closing brackets exceeds the count of opening brackets, the string becomes invalid. Therefore, we can maintain two variables, open and close, to track the number of opening and closing brackets. We avoid exploring paths where close > open. Once the string length reaches 2n, we add it to the result.

There are mainly 3 approach to solve this problem-

  1. Brute Force Method
  2. Backtracking Method
  3. Dynamic Programming Method

1. Brute Force Method

Generate all possible strings of ( and ) of length 2n and filter out the valid combinations by checking if they form well-balanced parentheses, resulting in high time complexity.

  • Time complexity: O(2^(2n) * n)
  • Space complexity: O(2^(2n) * n)

Code

2. Backtracking Method

Use recursion with backtracking to build valid parentheses strings by adding ( or ) only when it maintains a well-formed structure, efficiently pruning invalid paths.

  • Time complexity: O(4^n / (n)^1/2)
  • Space complexity: O(n)

Code

3. Dynamic Programming Method

Construct valid combinations using previously computed solutions for smaller values of n, combining them in different ways to form well-balanced parentheses for the current n.

  • Time complexity: O(4^n/(n)^1/2)
  • Space complexity: O(n)

Code

More Articles