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
Finding score of brackets in JavaScript
We are required to write a JavaScript function that takes in a balanced square bracket string as an argument and computes its score based on specific rules.
Scoring Rules
The bracket scoring follows these rules:
[]has score 1ABhas score A + B, where A and B are balanced bracket strings[A]has score 2 * A, where A is a balanced bracket string
Example Input and Output
For the input string '[][]':
Input: '[][]' Output: 2
This works because [] scores 1, and [][] is two adjacent bracket pairs, so 1 + 1 = 2.
Algorithm Implementation
The solution uses a stack-based approach to process the brackets and calculate scores:
const findScore = (str = '') => {
const arr = [];
for(const char of str) {
arr.push(char);
while(arr[arr.length - 1] === ']') {
arr.pop(); // Remove the ']'
if(arr[arr.length - 1] === '[') {
// Case: [] - empty brackets score 1
arr.pop(); // Remove the '['
arr.push(1);
} else {
// Case: [A] - multiply inner score by 2
let num = arr.pop();
while(arr[arr.length - 1] >= 1) {
num += arr.pop();
}
arr.pop(); // Remove the '['
arr.push(2 * num);
}
}
}
return arr.reduce((acc, a) => acc + a, 0);
};
// Test with different examples
console.log(findScore('[][]')); // 2
console.log(findScore('[[]]')); // 2
console.log(findScore('[[][]]')); // 4
2 2 4
How It Works
The algorithm processes each character:
Push opening brackets and characters onto the stack
When encountering a closing bracket
], calculate the scoreIf preceded by
[, it's an empty bracket pair (score 1)Otherwise, sum all numeric scores inside and multiply by 2
Finally, sum all remaining scores in the stack
Step-by-Step Example
For '[[]]':
Step 1: '[' ? stack: ['['] Step 2: '[' ? stack: ['[', '['] Step 3: ']' ? find '[', push 1 ? stack: ['[', 1] Step 4: ']' ? sum inner (1), multiply by 2 ? stack: [2] Result: 2
Conclusion
This stack-based solution efficiently calculates bracket scores by processing characters sequentially and applying the scoring rules. The algorithm handles nested and adjacent brackets correctly using a single pass through the string.
