Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
All ways of balancing n parenthesis in JavaScript
Problem
We are required to write a JavaScript function that takes in a number n. Our function should return an array showing all the ways of balancing n parenthesis.
For example, for n = 3, the output will be:
["()()()","(())()","()(())","(()())","((()))"]
Approach
We use a recursive backtracking approach where we keep track of how many opening and closing parentheses we can still use. At each step, we can add an opening parenthesis if we have any left, or a closing parenthesis if it would create a valid balance.
Example
Following is the code:
const generateParentheses = (n) => {
const result = [];
const backtrack = (left, right, current) => {
// Base case: no more parentheses to add
if (left === 0 && right === 0) {
result.push(current);
return;
}
// Add opening parenthesis if we have any left
if (left > 0) {
backtrack(left - 1, right + 1, current + "(");
}
// Add closing parenthesis if we have any to match
if (right > 0) {
backtrack(left, right - 1, current + ")");
}
};
// Start with n opening parentheses available
backtrack(n, 0, "");
return result;
};
// Generate all valid combinations for n = 3
const combinations = generateParentheses(3);
console.log(combinations);
Output
[ '((()))', '(()())', '(())()', '()(())', '()()()' ]
How It Works
The algorithm works by maintaining two counters:
- left: Number of opening parentheses we can still add
- right: Number of closing parentheses we need to add to balance
We start with left = n and right = 0. Each time we add an opening parenthesis, we decrease left and increase right. When we add a closing parenthesis, we only decrease right.
Alternative Implementation
Here's a cleaner version that directly passes n as the number of pairs:
function generateBalancedParentheses(n) {
const result = [];
function generate(current, open, close) {
// Base case: we've used all n pairs
if (current.length === n * 2) {
result.push(current);
return;
}
// Add opening parenthesis if we haven't used all n
if (open
n = 2: [ '(())', '()()' ]
n = 3: [ '((()))', '(()())', '(())()', '()(())', '()()()' ]
Conclusion
Both approaches use recursive backtracking to generate all valid parentheses combinations. The key insight is maintaining balance by ensuring we never add more closing parentheses than opening ones at any point.
