Valid Parentheses
Receives a string and checks whether its brackets are balanced and correctly nested. The valid pairs are (), [] and {}; any other character (letters, spaces, digits) is ignored. It scans the string left to right with a stack: every opening bracket is pushed, and every closing bracket must match the bracket on top of the stack — if it matches, that opening bracket is popped, otherwise the string is unbalanced. After the scan the string is balanced only if the stack is empty (no opening bracket was left unclosed). Returns true when every bracket is correctly paired and nested, and false otherwise.
Visualization
- Input
- Result
Algorithm code
// Balanced Brackets validator — a single pure function. Scans a string once and
// matches every closing bracket against the most recent unmatched opening
// bracket using a stack; characters that are not brackets are ignored. Returns
// whether all (), [] and {} are correctly paired and nested. No side effects.
// Each closing bracket maps to the opening bracket it must match.
const PAIRS = { ")": "(", "]": "[", "}": "{" };
/**
* @param {string} s - the string to validate, e.g. "a(b[c]d)e"
* @returns {boolean} true if every bracket is balanced and properly nested
*/
export function isBalanced(s) {
const stack = [];
for (const ch of s) {
if (ch === "(" || ch === "[" || ch === "{") {
stack.push(ch);
} else if (ch === ")" || ch === "]" || ch === "}") {
if (stack.pop() !== PAIRS[ch]) {
return false;
}
}
}
return stack.length === 0;
} FUNCTION isBalanced(s):
stack ← empty stack
pairs ← { ')' → '(' , ']' → '[' , '}' → '{' }
FOR EACH ch IN s:
IF ch is an opening bracket ( '(' , '[' , '{' ):
PUSH ch ONTO stack
ELSE IF ch is a closing bracket ( ')' , ']' , '}' ):
IF stack is empty OR POP stack ≠ pairs[ch]:
RETURN false
RETURN stack is empty