0
0
CsharpProgramBeginner · 2 min read

C# Program to Check Balanced Parentheses

Use a stack in C# to check balanced parentheses by pushing opening brackets with stack.Push() and popping when a matching closing bracket appears, returning true if all match and stack is empty at the end.
📋

Examples

Input()[]{}
OutputTrue
Input([)]
OutputFalse
Input
OutputTrue
🧠

How to Think About It

To check balanced parentheses, think of each opening bracket as something to remember until you find its matching closing bracket. Use a stack to keep track of these openings. When you see a closing bracket, check if it matches the last opening bracket you saw by popping from the stack. If it doesn't match or the stack is empty when you need to pop, the parentheses are not balanced. At the end, if the stack is empty, all parentheses matched correctly.
📐

Algorithm

1
Create an empty stack to hold opening brackets.
2
Go through each character in the input string.
3
If the character is an opening bracket, push it onto the stack.
4
If the character is a closing bracket, check if the stack is empty or the top does not match the closing bracket; if so, return false.
5
Pop the matching opening bracket from the stack.
6
After processing all characters, return true if the stack is empty; otherwise, return false.
💻

Code

csharp
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

1

Start with empty stack

stack = []

2

Read '(' - push to stack

stack = ['(']

3

Read ')' - pop and check match

stack before pop = ['('], popped = '(', matches ')'

4

Read '[' - push to stack

stack = ['[']

5

Read ']' - pop and check match

stack before pop = ['['], popped = '[', matches ']'

6

Read '{' - push to stack

stack = ['{']

7

Read '}' - pop and check match

stack before pop = ['{'], popped = '{', matches '}'

8

End of string - check stack empty

stack = [], return True

StepStack ContentCurrent CharActionResult
1[](Push '('['(']
2['('])Pop and checkMatch
3[][Push '['['[']
4['[']]Pop and checkMatch
5[]{Push '{'['{']
6['{']}Pop and checkMatch
7[]EndCheck empty stackTrue
💡

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 a counter for only parentheses
csharp
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("(()())"));
    }
}
This works only for parentheses '()' and is simpler but not for mixed brackets.
Using recursion to check pairs
csharp
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("()[]{}"));
    }
}
This removes pairs recursively but is less efficient for long strings.

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.

ApproachTimeSpaceBest For
Stack methodO(n)O(n)All bracket types, general use
Counter methodO(n)O(1)Only parentheses, simple cases
Recursive removalO(n^2)O(n)Small strings, educational purposes
💡
Use a stack to track opening brackets and match them with closing ones for balanced parentheses.
⚠️
Forgetting to check if the stack is empty before popping causes errors on unbalanced input.