Placing integers at correct index in JavaScript

We need to write a JavaScript function that takes a string containing only square brackets '[' and ']' and determines the minimum number of brackets to add to make it balanced.

Problem Statement

Given a string consisting of only '[' and ']' characters, find the minimum number of brackets that need to be added to make the string valid (properly balanced).

A valid bracket string means every opening bracket '[' has a corresponding closing bracket ']' that comes after it.

Example Input and Output

Input:

const str = '[]]';

Output:

1

Explanation: We need to add one '[' at the beginning to balance the extra ']', making it '[[]]'.

Algorithm Approach

We use a simple counting method:

  • Track unmatched opening brackets with a left counter
  • Track unmatched closing brackets with a right counter
  • For each '[': increment left
  • For each ']': if we have unmatched '[' (left > 0), match them by decrementing left; otherwise increment right

Implementation

const findAdditions = (str = '') => {
    let left = 0;   // unmatched opening brackets
    let right = 0;  // unmatched closing brackets
    
    for (let i = 0; i < str.length; i++) {
        if (str[i] === '[') {
            left += 1;
        } else if (str[i] === ']') {
            if (left > 0) {
                left -= 1;  // match with previous '['
            } else {
                right += 1; // unmatched ']'
            }
        }
    }
    
    return left + right;
};

// Test cases
console.log(findAdditions('[]]'));     // 1
console.log(findAdditions(']]['));     // 2  
console.log(findAdditions('[[]['));    // 1
console.log(findAdditions('[][]'));    // 0
1
2
1
0

How It Works

For the string '[]]':

  1. First '[': left = 1
  2. First ']': left > 0, so left = 0 (matched pair)
  3. Second ']': left = 0, so right = 1 (unmatched closing bracket)
  4. Result: left + right = 0 + 1 = 1

Key Points

  • The left variable counts opening brackets that need closing brackets
  • The right variable counts closing brackets that need opening brackets
  • The sum gives the minimum brackets needed to balance the string
  • Time complexity: O(n), Space complexity: O(1)

Conclusion

This algorithm efficiently finds the minimum brackets needed by tracking unmatched opening and closing brackets in a single pass. The total count represents the minimum additions required.

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

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements