![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
["()()()","(())()","()(())","(()())","((()))"]
Example
Following is the code −
const res = []; const buildcombination = (left, right, str) => { if (left === 0 && right === 0) { res.push(str); } if (left > 0) { buildcombination(left-1, right+1, str+"("); } if (right > 0) { buildcombination(left, right-1, str+")"); } } buildcombination(3, 0, ""); console.log(res);
Output
Following is the console output −
[ '((()))', '(()())', '(())()', '()(())', '()()()' ]
Advertisements