C# Program to Check Balanced Parentheses
stack.Push() and popping when a matching closing bracket appears, returning true if all match and stack is empty at the end.Examples
How to Think About It
Algorithm
Code
using System; using System.Collections.Generic; class Program { static bool IsBalanced(string s) { var stack = new Stack<char>(); foreach (var c in s) { if (c == '(' || c == '[' || c == '{') { stack.Push(c); } else if (c == ')' || c == ']' || c == '}') { if (stack.Count == 0) return false; char open = stack.Pop(); if ((c == ')' && open != '(') || (c == ']' && open != '[') || (c == '}' && open != '{')) return false; } } return stack.Count == 0; } static void Main() { string input = "()[]{}"; Console.WriteLine(IsBalanced(input)); } }
Dry Run
Let's trace the input "()[]{}" through the code
Start with empty stack
stack = []
Read '(' - push to stack
stack = ['(']
Read ')' - pop and check match
stack before pop = ['('], popped = '(', matches ')'
Read '[' - push to stack
stack = ['[']
Read ']' - pop and check match
stack before pop = ['['], popped = '[', matches ']'
Read '{' - push to stack
stack = ['{']
Read '}' - pop and check match
stack before pop = ['{'], popped = '{', matches '}'
End of string - check stack empty
stack = [], return True
| Step | Stack Content | Current Char | Action | Result |
|---|---|---|---|---|
| 1 | [] | ( | Push '(' | ['('] |
| 2 | ['('] | ) | Pop and check | Match |
| 3 | [] | [ | Push '[' | ['['] |
| 4 | ['['] | ] | Pop and check | Match |
| 5 | [] | { | Push '{' | ['{'] |
| 6 | ['{'] | } | Pop and check | Match |
| 7 | [] | End | Check empty stack | True |
Why This Works
Step 1: Use a stack to track openings
The stack remembers opening brackets until we find their matching closing ones.
Step 2: Match closing brackets with stack top
When a closing bracket appears, it must match the last opening bracket on the stack.
Step 3: Check stack empty at the end
If the stack is empty after processing, all brackets matched correctly, so return true.
Alternative Approaches
using System; class Program { static bool IsBalanced(string s) { int count = 0; foreach (var c in s) { if (c == '(') count++; else if (c == ')') { if (count == 0) return false; count--; } } return count == 0; } static void Main() { Console.WriteLine(IsBalanced("(()())")); } }
using System; class Program { static bool IsBalanced(string s) { if (string.IsNullOrEmpty(s)) return true; for (int i = 0; i < s.Length - 1; i++) { if ((s[i] == '(' && s[i+1] == ')') || (s[i] == '[' && s[i+1] == ']') || (s[i] == '{' && s[i+1] == '}')) { return IsBalanced(s.Remove(i, 2)); } } return false; } static void Main() { Console.WriteLine(IsBalanced("()[]{}")); } }
Complexity: O(n) time, O(n) space
Time Complexity
The program checks each character once, so time grows linearly with input size.
Space Complexity
The stack can hold up to all opening brackets, so space grows linearly in worst case.
Which Approach is Fastest?
The stack method is efficient and clear for all bracket types; counters are faster but limited to one bracket type.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Stack method | O(n) | O(n) | All bracket types, general use |
| Counter method | O(n) | O(1) | Only parentheses, simple cases |
| Recursive removal | O(n^2) | O(n) | Small strings, educational purposes |