
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Balancing Parentheses
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
Following is the code −
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
This will produce the following output on console −
2
Advertisements