Balanced brackets
Check whether every opening parenthesis, square bracket, and brace is closed in the correct order.
Course progress
Problem 27 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
text = "{[()]}"Expected output
True
What is happening?
Every closing bracket matches the most recent unmatched opening bracket: () closes first, then [], then {}. No brackets remain unmatched.
Solution strategy
Build the right mental model
Push opening symbols onto a stack. Each closing symbol must match the most recent opening symbol, and the stack must be empty at the end.
Core concepts
stack · parsing
Complexity
Time O(n), space O(n).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for balanced-brackets
using System;
using System.Collections.Generic;
class Program
{
static bool IsBalanced(string text)
{
var expected = new Stack<char>();
foreach (char symbol in text)
{
if (symbol == '(') expected.Push(')');
else if (symbol == '[') expected.Push(']');
else if (symbol == '{') expected.Push('}');
else if (symbol == ')' || symbol == ']' || symbol == '}')
{
if (expected.Count == 0 || expected.Pop() != symbol) return false;
}
}
return expected.Count == 0;
}
static void Main()
{
Console.WriteLine(IsBalanced("{[()]}") );
}
}Knowledge check
Questions students often ask
What is the main idea behind balanced brackets?
Push opening symbols onto a stack. Each closing symbol must match the most recent opening symbol, and the stack must be empty at the end.
What is the time and space complexity of this solution?
Time O(n), space O(n).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.