How to Generate Balanced Brackets in Python?

Feature Img Balanced Brackets

In this tutorial, we will be understanding a very interesting problem known as Generate Balanced Brackets. Balanced Brackets imply that the number of opening and closing brackets are exactly equal.

Understanding the Concept of Generating Balanced Brackets

We will be handling a number of variables namely, the value of n (given by the user), output string, count of opening and closing brackets, and the iterator.

In every recursion call, the output string will be manipulated by inserting either an opening or closing bracket. And according to it, the count of opening and closing brackets is increased and the function is called recursively.

We keep checking the balancing of brackets in every recursive call.

Read more about Recursion: Recursion in Python

Generate Balanced Brackets in Python

def all_balanced(n,output,itr,count_open,count_close):

    # base case
    if(itr == 2*n):

    # Insert open curly bracket    
        output = output[:itr] + '{' + output[itr+1:]
    # Insert closing curly brackwt
        output = output[:itr] + '}' + output[itr+1:]


n= int(input())

Sample Output

The output below is the result when the value of n is equal to 4. This means there will be 4 opening and 4 closing brackets.


I hope you are clear with the concept, problem, and code implementation of the Balanced brackets problem.

Thank you for reading! Happy learning! 🙂