- Trending Categories
- 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
Finding the balance of brackets in JavaScript
Given a string that consists of only two types of characters: "(" and ")". We are required to write a function that takes in one such string and balances the parentheses by inserting either a "(" or a ")" as many times as necessary. The function should then return the minimum number of insertions made in the string to balance it.
For example: If the string is −
const str = '()))';
Then the output should be 2, because by prepending '((', we can balance the string.
Example
The code for this will be −
const str = '()))'; const balanceParanthesis = str => { let paren = []; for (let i = 0; i < str.length; i++) { if (str[i] === "(") { paren.push(str[i]); } else if (str[i] === ")") { if (paren[paren.length - 1] === "("){ paren.pop(); }else { paren.push("#"); }; }; } return paren.length; } console.log(balanceParanthesis(str));
Output
The output in the console will be −
2
Advertisements