How to print all possible balanced parentheses for an expression?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Printing all possible balanced parentheses is a classic problem encountered in computer science, often used to test recursion and backtracking capabilities in interview settings and coding competitions. This problem involves generating all valid combinations of parentheses given a certain number, `n`, which represents pairs of parentheses. Balanced parentheses imply that each opening parenthesis '(' has a corresponding closing parenthesis ')', and the parentheses are correctly nested.
This article aims to explore methods to solve this problem, focusing primarily on recursive approaches and providing insights and examples to enhance understanding.
Problem Explanation
Given a number `n`, representing the number of pairs of parentheses, the goal is to generate all combinations of balanced parentheses. For example, if `n = 3`, the valid combinations are:
- `((()))`
- `(()())`
- `(())()`
- `()(())`
- `()()()`
Algorithmic Approach
The primary approach to solve this problem is through recursion with backtracking. The recursive approach works by keeping track of the number of opening and closing brackets used so far and ensuring that we do not violate the balance condition. The key condition here is that the number of closing brackets cannot exceed the number of opening brackets at any time during the construction of a sequence. Additionally, we cannot use more than `n` opening and closing brackets.
Here is the procedure broken down into steps:
- Initialize variables: Start with an empty string, a count of opening parentheses, and a count of closing parentheses.
- Recursive Function: Define a recursive function that will build the parentheses sequences.
- Stopping Condition: If both counts of opening and closing parentheses reach `n`, a valid sequence is formed.
- Recursive Calls:
- If the number of opening parentheses is less than `n`, add an opening parenthesis and make a recursive call.
- If the number of closing parentheses is less than the number of opening parentheses, add a closing parenthesis and make a recursive call.
- Backtrack: After exploring one possibility to completion, backtrack to explore other possibilities.
Example Implementation
Let's dive into a Python implementation of the above logic:
- Parsing expressions across various programming languages to ensure syntax correctness.
- Formatting and validating data in JSON and XML.
- String matching algorithms, especially in compiler construction and runtime interpreters.
Related reading
- How to properly define hash function for a list of objects?
- How to prove max number of connection between n nodes is nn-1/2
- How to Prove one Random Number Generator is Better Than Another?
- How to prove that a problem is NP complete?
- How to randomly choose sample points that maximize space occupation?
- How to randomly shuffle a list that has more permutations than the PRNG's period?
- How to provide most relevant results with Multiple Factor Weighted Sorting
- How to rank a million images with a crowdsourced sort

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.