Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
leftcounter - Track unmatched closing brackets with a
rightcounter - For each '[': increment
left - For each ']': if we have unmatched '[' (left > 0), match them by decrementing
left; otherwise incrementright
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 '[]]':
- First '[': left = 1
- First ']': left > 0, so left = 0 (matched pair)
- Second ']': left = 0, so right = 1 (unmatched closing bracket)
- Result: left + right = 0 + 1 = 1
Key Points
- The
leftvariable counts opening brackets that need closing brackets - The
rightvariable 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.
