DATA STRUCTURES PROGRAM • STACKS & EXPRESSIONS

Check Balanced Parentheses Using a Stack

Learn how to check balanced parentheses using a stack using a clear C program.

BeginnerStackLIFOpush/pop

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Balanced.

COMPLETE C PROGRAM

Complete C implementation

dsa-balanced-parentheses.c
Open in compiler
#include <stdio.h>
#include <stddef.h>

int matches(char opening, char closing)
{
    return (opening == '(' && closing == ')') ||
           (opening == '[' && closing == ']') ||
           (opening == '{' && closing == '}');
}

int main(void)
{
    const char expression[] = "{[a+(b*c)]-d}";
    char stack[50];
    int top = -1, balanced = 1;
    for (size_t index = 0; expression[index] != '\0'; index++) {
        char token = expression[index];
        if (token == '(' || token == '[' || token == '{') stack[++top] = token;
        else if (token == ')' || token == ']' || token == '}') {
            if (top < 0 || !matches(stack[top--], token)) { balanced = 0; break; }
        }
    }
    if (top != -1) balanced = 0;
    puts(balanced ? "Balanced." : "Not balanced.");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Balanced.
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Push openings and require every closing symbol to match the latest unmatched opening.
  3. Display the computed result.

Push openings and require every closing symbol to match the latest unmatched opening.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.