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
Parse and balance angle brackets problem in JavaScript
In JavaScript, determining whether angle brackets in a string are properly balanced is a common problem when working with HTML, XML, or template parsing. This problem requires checking that every opening angle bracket '<' has a corresponding closing bracket '>' in the correct order.
What is a Stack-based Approach?
The stack-based approach uses a Last In, First Out (LIFO) data structure to track opening brackets. When we encounter an opening bracket, we push it onto the stack. When we find a closing bracket, we check if there's a matching opening bracket at the top of the stack and pop it if found.
Think of it like stacking plates ? you can only add or remove plates from the top of the stack.
Understanding the Problem
We need to verify that angle brackets are properly balanced and nested. For every opening bracket '<', there must be a corresponding closing bracket '>' that appears later in the string. Brackets must also be properly nested without crossing each other.
Algorithm Steps
Step 1: Create a function that accepts an input string parameter
Step 2: Initialize an empty stack array
Step 3: Iterate through each character in the input string
Step 4: If character is '<', push it onto the stack
Step 5: If character is '>', check if stack is empty (unmatched closing bracket). If not empty, pop the matching opening bracket
Step 6: Return true if stack is empty (all brackets matched), false otherwise
Implementation
function isBalanced(input) {
const stack = [];
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (char === '<') {
// Push opening angle bracket onto the stack
stack.push(char);
} else if (char === '>') {
if (stack.length === 0) {
// Found a closing angle bracket without opening bracket
return false;
}
// Pop the matching opening angle bracket
stack.pop();
}
}
// Return true if all brackets are matched (stack is empty)
return stack.length === 0;
}
// Test cases
console.log(isBalanced("<div>")); // Simple balanced pair
console.log(isBalanced("<div")); // Missing closing bracket
console.log(isBalanced("<<div>>>")); // Unbalanced nesting
console.log(isBalanced("<div></div>")); // Properly nested tags
console.log(isBalanced("><")); // Wrong order
true false false true false
Enhanced Version with Better Error Reporting
function checkBracketBalance(input) {
const stack = [];
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (char === '<') {
stack.push({ char: char, position: i });
} else if (char === '>') {
if (stack.length === 0) {
return {
balanced: false,
error: `Unmatched closing bracket at position ${i}`
};
}
stack.pop();
}
}
if (stack.length > 0) {
return {
balanced: false,
error: `${stack.length} unmatched opening bracket(s)`
};
}
return { balanced: true, error: null };
}
// Test the enhanced version
const result1 = checkBracketBalance("<div><span></span></div>");
const result2 = checkBracketBalance("<div><span>");
console.log("Test 1:", result1);
console.log("Test 2:", result2);
Test 1: { balanced: true, error: null }
Test 2: { balanced: false, error: '2 unmatched opening bracket(s)' }
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Single pass through input string |
| Space | O(n) | Stack stores up to n/2 opening brackets in worst case |
Common Use Cases
This algorithm is useful for:
- HTML/XML tag validation
- Template engine bracket matching
- Code editor syntax highlighting
- Parser preprocessing
Conclusion
The stack-based approach provides an efficient O(n) solution for checking balanced angle brackets. This technique is fundamental for parsing markup languages and can be extended to handle multiple bracket types simultaneously.
