
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Finding score of brackets in JavaScript
- Parse and balance angle brackets problem in JavaScript
- Balance a string after removing extra brackets in C++
- Validating brackets in a string in JavaScript
- Find digits between brackets in JavaScript RegExp?
- Finding the inclination of arrays in JavaScript
- What is the use of ()(parenthesis) brackets in accessing a function in JavaScript?
- JavaScript RegExp return values between various square brackets? How to get value brackets?
- Finding the rotation of an array in JavaScript
- Finding the continuity of two arrays in JavaScript
- Finding the mid of an array in JavaScript
- Finding the final direction of movement in JavaScript
- Finding persistence of number in JavaScript
- Finding sum of multiples in JavaScript
- How to find character between brackets in JavaScript RegExp?

Advertisements