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.

How It Works

The algorithm uses a stack-like approach to track unmatched parentheses:

  • When we encounter '(', we push it to track an opening bracket
  • When we encounter ')', we check if there's a matching '(' to pop
  • If no matching '(' exists, we mark it as an unmatched ')' using a placeholder "#"
  • The final array length represents the minimum insertions needed

Example

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

2

Step-by-Step Execution

Let's trace through the example '()))' :

const traceBalance = str => {
    let paren = [];
    console.log(`Processing: "${str}"`);
    
    for (let i = 0; i < str.length; i++) {
        console.log(`Character ${i}: '${str[i]}'`);
        
        if (str[i] === "(") {
            paren.push(str[i]);
            console.log(`  Pushed '(' - Stack: [${paren.join(', ')}]`);
        } else if (str[i] === ")") {
            if (paren[paren.length - 1] === "("){
                paren.pop();
                console.log(`  Matched pair - Stack: [${paren.join(', ')}]`);
            }else {
                paren.push("#");
                console.log(`  Unmatched ')' - Stack: [${paren.join(', ')}]`);
            }
        }
    }
    
    console.log(`Final insertions needed: ${paren.length}`);
    return paren.length;
}

traceBalance('()))');

Output

Processing: "()))"
Character 0: '('
  Pushed '(' - Stack: [(]
Character 1: ')'
  Matched pair - Stack: []
Character 2: ')'
  Unmatched ')' - Stack: [#]
Character 3: ')'
  Unmatched ')' - Stack: [#, #]
Final insertions needed: 2

More Examples

// Test different bracket patterns
const testCases = ['(()', '())', '((()))', ')))(((('];

testCases.forEach(test => {
    const result = balanceParanthesis(test);
    console.log(`"${test}" needs ${result} insertions`);
});

Output

"(((" needs 3 insertions
"())" needs 1 insertions
"((()))" needs 0 insertions
")))(((()" needs 7 insertions

Conclusion

This algorithm efficiently finds the minimum bracket insertions needed by tracking unmatched opening and closing parentheses. The time complexity is O(n) and space complexity is O(n) in the worst case.

Updated on: 2026-03-15T23:19:00+05:30

398 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements