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):
print(output)
return
# Insert open curly bracket
if(count_open<n):
output = output[:itr] + '{' + output[itr+1:]
all_balanced(n,output,itr+1,count_open+1,count_close)
# Insert closing curly brackwt
if(count_open>count_close):
output = output[:itr] + '}' + output[itr+1:]
all_balanced(n,output,itr+1,count_open,count_close+1)
return
n= int(input())
all_balanced(n,"",0,0,0)
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! 🙂