AlgoTales · Roadmap

Balanced parentheses

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Balanced parentheses means every opening bracket has a matching closing bracket in the right order, like (a[b]{c}). A stack checks this neatly: push each opener, and when a closer appears the top of the stack must be its partner.

Practical use cases

  • Web app: A code editor flagging a missing bracket. An online code editor underlines an error when you forget a closing brace. Behind the scenes it pushes each opening bracket onto a stack and pops when it sees a closing one. If the stack is not empty at the end, or the types do not match, the editor knows exactly where to underline.
  • Web app: Validating HTML or a formula before saving. A CMS lets editors paste HTML, and a spreadsheet-like page accepts formulas such as =SUM((A1+B1)*2). Both must be checked before saving. The same push-and-pop check finds an unclosed tag or bracket, so users get a message at once instead of a broken page later.
  • System: Compilers and JSON or XML parsers. Compilers, JSON parsers and XML validators all require that nested structures close in the right order. A stack remembers what is still open, so a closing tag that does not match the most recent open one is spotted straight away.

The story: Plates at the Wedding Buffet

At Mira's cousin's wedding, the caterer stacked clean plates in a tall pile. Guests always took the plate on top, never from the bottom. The last plate placed was the first one taken. Last in, first out.

A strange game started among the kids: whenever someone opened a bracket in a sentence, like "(" or "[", they placed a plate. Whenever someone closed a bracket, they had to take the top plate and check it was the matching type.

If a closing "]" arrived but the top plate said "(", the sentence was broken. If plates were left over at the end, some bracket was never closed. When the pile was perfectly empty at the finish, every bracket had found its partner. That is exactly how your code editor checks your brackets.

How to spot this problem, and where you need it

Text contains pairs that open and close, and you must check that each opened pair is closed in the right order, with the most recently opened one closed first.

Signs you need it

  • The problem has brackets, quotes, HTML tags, begin and end markers or any nested open and close pairs.
  • A simple counter of opens and closes works for one type of bracket but fails when different kinds are mixed, like "([)]".
  • You must report where the first mismatch is, not just that something is wrong.

Where to use it in a project

  • Form fields that accept formulas, templates or custom expressions entered by users.
  • Linting and highlighting of code, HTML, JSON or Markdown in browser editors.
  • Template engines and import tools that check nested blocks before processing.

The solution

Go through the text one character at a time. For each opening bracket, push it on the stack. For each closing bracket, check that the stack is not empty and that the top is its matching opener; if so, pop it, otherwise report a mismatch at this position. After the last character the stack must be empty; if not, some opener was never closed.

Payoff: Before: users found broken formulas or pages only after saving. After: the exact bad position is reported in one pass while they type.

Explain it like I am 8

A stack is a pile of pancakes: you can only add to the top and take from the top. When you see an opening bracket, put it on the pile. When you see a closing bracket, the top pancake must be its matching opener. If it is not, something is wrong.

How it works, step by step

  1. Read characters left to right.
  2. Opening bracket ( [ { → push it onto the stack.
  3. Closing bracket ) ] } → pop the top. It must be the matching opener, or the text is not balanced.
  4. At the end the stack must be empty. Leftover openers were never closed.

The code in four languages

PHP

<?php
function isBalanced(string $text): bool {
    $pairs = [')' => '(', ']' => '[', '}' => '{'];
    $stack = [];

    foreach (str_split($text) as $ch) {
        if (in_array($ch, $pairs, true)) {
            $stack[] = $ch;                          // push opener
        } elseif (isset($pairs[$ch])) {
            if (array_pop($stack) !== $pairs[$ch]) { // pop and compare
                return false;
            }
        }
    }
    return count($stack) === 0;                      // nothing left over
}

var_dump(isBalanced('{[()]}'));   // true
var_dump(isBalanced('([)]'));     // false

JavaScript

function isBalanced(text) {
  const pairs = { ')': '(', ']': '[', '}': '{' };
  const stack = [];

  for (const ch of text) {
    if (Object.values(pairs).includes(ch)) {
      stack.push(ch);                         // push opener
    } else if (pairs[ch]) {
      if (stack.pop() !== pairs[ch]) {        // pop and compare
        return false;
      }
    }
  }
  return stack.length === 0;                  // nothing left over
}

console.log(isBalanced('{[()]}'));   // true
console.log(isBalanced('([)]'));     // false

Java

import java.util.*;

public class Main {
    static boolean isBalanced(String text) {
        Map<Character, Character> pairs = Map.of(')', '(', ']', '[', '}', '{');
        Deque<Character> stack = new ArrayDeque<>();

        for (char ch : text.toCharArray()) {
            if (pairs.containsValue(ch)) {
                stack.push(ch);                          // push opener
            } else if (pairs.containsKey(ch)) {
                if (stack.isEmpty() || stack.pop() != pairs.get(ch)) {   // pop and compare
                    return false;
                }
            }
        }
        return stack.isEmpty();                          // nothing left over
    }

    public static void main(String[] args) {
        System.out.println(isBalanced("{[()]}"));   // true
        System.out.println(isBalanced("([)]"));     // false
    }
}

Go

package main

import "fmt"

func isBalanced(text string) bool {
	pairs := map[rune]rune{')': '(', ']': '[', '}': '{'}
	openers := map[rune]bool{'(': true, '[': true, '{': true}
	var stack []rune

	for _, ch := range text {
		if openers[ch] {
			stack = append(stack, ch) // push opener
		} else if want, isCloser := pairs[ch]; isCloser {
			if len(stack) == 0 || stack[len(stack)-1] != want { // pop and compare
				return false
			}
			stack = stack[:len(stack)-1]
		}
	}
	return len(stack) == 0 // nothing left over
}

func main() {
	fmt.Println(isBalanced("{[()]}")) // true
	fmt.Println(isBalanced("([)]"))   // false
}

Time: O(n) · Extra space: O(n). One pass over the text; in the worst case (all openers) the stack holds n items.

Watch out for

  • Popping from an empty stack when the text starts with a closer, like ")(". Handle that case.
  • Forgetting the final check. "((" never fails mid-way but is still unbalanced.

Quick check

  1. Which item does a stack give back first?
    • The oldest
    • The newest
    • The biggest
  2. Is "([)]" balanced?
    • Yes
    • No
  3. At the end of a valid string, the stack should be…
    • Full
    • Empty
    • Half full