JS Built-ins
Algorithmsintermediate

Balanced Brackets Check

πŸ“– Usage Example
function isBalanced(s) {
  const stack = [];
  for (const c of s) {
    if (c === '(') stack.push(c);
    else if (!stack.pop()) return false;
  }
  return stack.length === 0;
}

Use a stack to verify balanced brackets by pushing opens and popping on closes.

Balanced Brackets Check

Check if a string containing brackets is balanced. Each opening bracket must have a corresponding closing bracket, and brackets must be properly nested.

Valid: "()", "()[]{}", "([{}])" Invalid: "([)]", "(()", "())"

Algorithm:

  1. Use a stack to track opening brackets
  2. For each character:
    • If opening bracket, push to stack
    • If closing bracket, check if it matches the top of stack
  3. Stack should be empty at the end
function isBalanced(s: string): boolean {
  // Return true if brackets are balanced
}

isBalanced('([{}])') // true
isBalanced('([)]') // false
πŸ’‘ Hints (5)
  • β€’ Use a stack to store opening brackets.
  • β€’ For each opening bracket, push it to the stack.
  • β€’ For each closing bracket, check if it matches the top of the stack.
  • β€’ Use an object to map closing brackets to opening brackets.
  • β€’ Stack should be empty at the end.