beginner · stacks · strings · parsing

Do the brackets close properly?

Problem

A configuration line contains only the brackets ( ) [ ] { }. It is well formed if every opening bracket is closed by the same kind, in the right order. Decide whether a line is well formed.

Constraints

  • 0 ≤ length ≤ 32
  • only the six bracket characters

Examples

"([]{})" → true

"([)]" → false — ] closes ( : wrong kind.

"((" → false — Unclosed.

Show the solution

Stack of open brackets

A closing bracket must match the last unclosed opening bracket: last in, first out.

Why it is correct

The stack always holds the unclosed opening brackets in order. A closing bracket is valid exactly when it matches the top; the line is well formed exactly when every closing bracket was valid and nothing is left open.

Complexity

Time O(n), extra space O(n). Each character is pushed or popped once.

Edge cases

  • Empty line: well formed.
  • Starts with a closing bracket: the stack is empty, fail immediately.
  • Only openings: the final emptiness check fails.

Common mistakes

  • Forgetting the final emptiness check.
  • Popping an empty stack (crash) instead of returning false.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class BalancedBrackets
{
    private static char OpenerOf(char close) => close switch { ')' => '(', ']' => '[', _ => '{' };
 
    /// <summary>Whether every bracket is closed by the same kind in the right order. O(n) time and space.</summary>
    public static bool IsBalanced(string line)
    {
        var stack = new Stack<char>();
        foreach (char c in line)
        {
            if (c is '(' or '[' or '{')
                stack.Push(c);
            else if (stack.Count == 0 || stack.Pop() != OpenerOf(c))
                return false;
        }
        return stack.Count == 0;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/BalancedBrackets.cs

OPENER = {")": "(", "]": "[", "}": "{"}
 
 
def is_balanced(line: str) -> bool:
    """Whether every bracket is closed by the same kind in the right order. O(n) time and space."""
    stack: list[str] = []
    for char in line:
        if char in "([{":
            stack.append(char)
        elif not stack or stack.pop() != OPENER[char]:
            return False
    return not stack

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/balanced_brackets.py

package dev.bekadan.dsa.problems;
 
import java.util.ArrayDeque;
import java.util.Deque;
 
public final class BalancedBrackets {
    private BalancedBrackets() {
    }
 
    private static char openerOf(char close) {
        return close == ')' ? '(' : close == ']' ? '[' : '{';
    }
 
    /** Whether every bracket is closed by the same kind in the right order. O(n) time and space. */
    public static boolean isBalanced(String line) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char c : line.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else if (stack.isEmpty() || stack.pop() != openerOf(c)) {
                return false;
            }
        }
        return stack.isEmpty();
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/BalancedBrackets.java

#pragma once
 
#include <string_view>
#include <vector>
 
namespace bekadan::dsa::problems {
 
// Whether every bracket is closed by the same kind in the right order. O(n) time and space.
inline bool balanced_brackets(std::string_view line) {
    const auto opener_of = [](char close) { return close == ')' ? '(' : close == ']' ? '[' : '{'; };
    std::vector<char> stack;
    for (char c : line) {
        if (c == '(' || c == '[' || c == '{') {
            stack.push_back(c);
        } else {
            if (stack.empty() || stack.back() != opener_of(c))
                return false;
            stack.pop_back();  // matched: the pair is closed
        }
    }
    return stack.empty();
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/balanced_brackets.hpp