Grad shape
Grad shape

Generate Parentheses

Get started
hero image
    🙏

    জয়  শ্রী  রাম

    🕉





Problem Statement:


Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:
Input: n = 1
Output: ["()"]

Solution:


  • NOTE: I highly recommend going through the Backtracking chapters in the order they are given in the Index page to get the most out of it and be able to build a rock-solid understanding.


If you are familiar with our backtracking template then you would be easily come up with a quick solution for this problem just by making the below two observations:

We need to ask ourselves two questions:
  • When can we add an opening brace "(" to a given empty or non-empty partial solution ?
  • When can we add a closing brace ")" to a given empty or non-empty partial solution ?
When we have n = 3 (you can take whatever n you want) below are all the configurations we can get: "((()))", "(()())", "(())()", "()(())", "()()()"

Looking at the patterns carefully, we can conclude:
  1. We always have room for appending one more opening brace "(" to a given partial solution as long as partial solution contains less than n opening braces.

    "(" can be added to an empty partial solution.

    Keep in mind we cannot have more than n opening braces in our solution.

  2. We can append closing brace ")" to our partial solution only when we have less number of closing braces than opening braces in our current partial solution.

    ")" cannot be added to an empty partial solution.

This leads to the below code. I have put additional logic in the inline comment for your better understanding.

Java Code:



Login to Access Content



Python Code:



Login to Access Content




Time Complexity:




Please subscribe to access the complexity analysis.




Don't forget to take in-depth look at the other backtracking problems because that is what would make you comfortable with using the backtracking template and master the art of Backtracking:


Instructor: