Full answer
A string such as {[()]} is balanced when every opening bracket is closed by the same type, in the right order. Counting brackets is not enough: ([)] has equal counts but is wrong. The nested structure needs a stack, which gives last in, first out order.
Algorithm:
- Create a Map from each closing bracket to its opening bracket:
)to(,]to[,}to{. - For each character: if it is an opening bracket, push it (with its position if you want error reports). If it is a closing bracket, pop the stack. If the stack was empty or the popped value is not the expected opening bracket, the string is invalid.
- Ignore other characters if the input can contain normal text, which is the case for code.
- After the loop, the string is balanced only if the stack is empty. Otherwise some brackets were never closed.
Complexity is O(n) time and O(n) space in the worst case, when the input is all opening brackets. Quick checks help: an odd length (when the input has only brackets) can never be balanced.
Using a plain JavaScript array as a stack is idiomatic: push and pop are O(1).
Follow-ups that are common: return the index of the first error (store indexes on the stack), find the minimum number of removals to make a string balanced (a variation with a counter), and extend the rule to HTML tags or to quotes that must not be counted inside strings. For a single bracket type, a counter is enough, and it must never go below zero.
This is the same idea that parsers use to check nesting, and it is a good bridge to the call stack and recursion.
const PAIRS = new Map([[')', '('], [']', '['], ['}', '{']]);
const OPENERS = new Set(PAIRS.values());
function checkBrackets(text) {
const stack = [];
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (OPENERS.has(ch)) {
stack.push({ ch, i });
} else if (PAIRS.has(ch)) {
const top = stack.pop();
if (!top) return { valid: false, reason: `unexpected ${ch} at ${i}` };
if (top.ch !== PAIRS.get(ch)) return { valid: false, reason: `${ch} at ${i} does not match ${top.ch} at ${top.i}` };
}
}
if (stack.length > 0) {
const open = stack[stack.length - 1];
return { valid: false, reason: `${open.ch} at ${open.i} is never closed` };
}
return { valid: true, reason: 'balanced' };
}
const isBalanced = (text) => checkBrackets(text).valid;
for (const sample of ['{[()]}', '([)]', '((', '())', '', 'a(b[c]{d})e', ']']) {
console.log(JSON.stringify(sample).padEnd(16), checkBrackets(sample));
}
function minAddsForParentheses(text) {
let open = 0;
let adds = 0;
for (const ch of text) {
if (ch === '(') open++;
else if (ch === ')') open > 0 ? open-- : adds++;
}
return adds + open;
}
console.log(isBalanced('{[()]}'), isBalanced('(]'), minAddsForParentheses('())('), minAddsForParentheses('((('));Run with Node.js v24.22.1 as js-122.js; two runs gave identical output. Output: "{[()]}" { valid: true, reason: 'balanced' } "([)]" { valid: false, reason: ') at 2 does not match [ at 1' } "((" { valid: false, reason: '( at 1 is never closed' } "())" { valid: false, reason: 'unexpected ) at 2' } "" { valid: true, reason: 'balanced' } "a(b[c]{d})e" { valid: true, reason: 'balanced' } "]" { valid: false, reason: 'unexpected ] at 0' } true false 2 3
Key points
- Push opening brackets; on a closing bracket pop and compare with the expected pair.
- Balanced means no mismatch and an empty stack at the end.
- Counting alone fails for ([)] because order matters.
- O(n) time, O(n) space; an array with push and pop works as the stack.
- Store positions on the stack to report the first error; one bracket type needs only a counter.
Common mistakes
- Comparing counts of brackets instead of using a stack.
- Forgetting the empty stack check at the end.
- Popping from an empty stack and not handling it.
- Treating brackets inside string literals as real brackets when the input is code.
Follow-ups
- How would you find the longest valid parentheses substring?
- How would the solution change for HTML tags?
- How is this related to the call stack?
Tips
- Show ([)] as the case where counting fails.
- Return a reason and position, since many interviewers ask for it.
- Check the stack at the end.