Skip to study material
← Question index

QUESTION 12

Explain balancing parentheses, brackets and braces using a stack.

5 marks

Answer in brief

A bracket-balancing algorithm checks that nested grouping symbols close in the reverse order in which they open.

Algorithm

  1. Push each opening (, [ or { symbol.
  2. For a closing symbol, reject an empty stack.
  3. Pop the latest opening and require the matching type.
  4. After the complete input, accept only an empty stack.

Examples

{[()]} is balanced. ([)] is not: the closing ) arrives while [ is on top. A simple equal-count check would miss that incorrect nesting. An unmatched closing symbol fails immediately, and leftover openings fail at the end.

Stack role

The last unclosed opening must be the first one closed, which is exactly LIFO order. The stack records both the number and types of pending openings. A counter alone cannot describe every nested type combination.

Scope of the program

The example checks grouping symbols in a bounded ordinary line and ignores other characters. It is not a complete C lexer: brackets inside string literals or comments are not specially ignored. State this distinction when applying the algorithm to source-code validation.

Complexity

A line of n characters is scanned once. Each bracket is pushed or popped once, giving O(n) time. If every character is an opening symbol, the pending stack can contain O(n) symbols. The fixed-size demonstration stack matches its input capacity to avoid overflow.

Complete C example

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
#include <string.h>
int read_line(char s[80])
{
    if (fgets(s, 80, stdin) == NULL) { return 0; }
    char *newline = strchr(s, '\n');
    if (newline != NULL) { *newline = '\0'; return 1; }
    int ch = getchar();
    if (ch == '\n' || ch == EOF) { return 1; }
    while ((ch = getchar()) != '\n' && ch != EOF) { }
    return 0;
}
int balanced(const char text[])
{
    char stack[80]; int top = -1;
    for (int i = 0; text[i] != '\0'; ++i) {
        char ch = text[i];
        if (ch == '(' || ch == '[' || ch == '{') { stack[++top] = ch; }
        else if (ch == ')' || ch == ']' || ch == '}') {
            if (top < 0) { return 0; }
            char opening = stack[top--];
            if ((ch == ')' && opening != '(') || (ch == ']' && opening != '[') || (ch == '}' && opening != '{')) { return 0; }
        }
    }
    return top == -1;
}

int main(void)
{
    char text[80];
    if (!read_line(text)) { puts("Invalid input"); return 1; }
    puts(balanced(text) ? "Balanced" : "Unbalanced");
    return 0;
}

Sample input and output

Input

{[()]}

Output

Balanced