📌 Information & Algorithm

Algorithm

Follow these steps to match parentheses:

  1. Scan the expression from left to right.
  2. If a left parenthesis ( is encountered, push its position into the stack.
  3. If a right parenthesis ) is encountered, pop an element from the stack.
  4. If the stack is empty while processing a right parenthesis, then that parenthesis is unmatched.
  5. After scanning the entire expression, if the stack is not empty, then the remaining opening parentheses are unmatched.

💻 Program Code

import java.util.Stack;

public class ParenthesisMatch {

    public static void printMatchedPairs(String expr) {

        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < expr.length(); i++) {

            char ch = expr.charAt(i);

            if (ch == '(') {
                stack.push(i);
            }

            else if (ch == ')') {

                if (!stack.isEmpty()) {

                    int j = stack.pop();

                    System.out.println(
                        ") at index " + i +
                        " matched with ( at index " + j
                    );
                }
                else {
                    System.out.println(
                        ") at index " + i +
                        " is UNMATCHED!"
                    );
                }
            }
        }

        while (!stack.isEmpty()) {

            System.out.println(
                "( at index " +
                stack.pop() +
                " is UNMATCHED!"
            );
        }
    }

    public static void main(String[] args) {

        String expr1 = "(x+(y-z)*w)";
        String expr2 = "((a+b/(c-d))";

        System.out.println("Expression: " + expr1);
        printMatchedPairs(expr1);

        System.out.println("\nExpression: " + expr2);
        printMatchedPairs(expr2);
    }
}
                        

📘 Explanation

Parenthesis Matching Using Stack in Java

The Parenthesis Matching Problem is used to check whether every opening parenthesis ( has a corresponding closing parenthesis ) in an expression. A Stack is the most suitable data structure for solving this problem because it follows the LIFO (Last In First Out) principle.



Dry Run Example

Expression

(x+(y-z)*w)

Index Positions

0 1 2 3 4 5 6 7 8 9 10

( x + ( y - z ) * w )

Step 1

At index 0, the character is (. Push index 0 into the stack.

Stack = [0]

Step 2

At index 3, another opening parenthesis is found. Push index 3 into the stack.

Stack = [0, 3]

Step 3

At index 7, a closing parenthesis is found. Pop the top element from the stack.

) at index 7 matched with ( at index 3
Stack = [0]

Step 4

At index 10, another closing parenthesis is found. Pop the top element from the stack.

) at index 10 matched with ( at index 0
Stack = []

Final Output

) at index 7 matched with ( at index 3
) at index 10 matched with ( at index 0

Example with Unmatched Parentheses

Expression

((a+b/(c-d))

Index Positions

0 1 2 3 4 5 6 7 8 9 10 11

( ( a + b / ( c - d ) )

Matching Process

) at index 10 matched with ( at index 6
) at index 11 matched with ( at index 1

After processing all characters, one opening parenthesis remains in the stack.

Stack = [0]

Therefore, the output will be:

( at index 0 is UNMATCHED!

Why Do We Use a Stack?

A stack follows the LIFO (Last In First Out) principle. The most recently inserted opening parenthesis should be matched first when a closing parenthesis is encountered.

Push first (
Push second (

Stack:
[0, 3]

When ')' appears:

Pop 3 first
Pop 0 later

This behavior perfectly matches the rule that the most recently opened parenthesis must be closed first. Therefore, a stack is the ideal data structure for solving the parenthesis matching problem.


Time Complexity

Operation Complexity
Traversing the Expression O(n)
Push Operation O(1)
Pop Operation O(1)
Overall Complexity O(n)

Here, n represents the length of the expression.


Applications of Parenthesis Matching

  • Compiler Design
  • Syntax Checking
  • Expression Evaluation
  • HTML/XML Tag Validation
  • Code Editors such as VS Code, Eclipse, and IntelliJ IDEA
  • Mathematical Expression Verification

Conclusion

The Parenthesis Matching Problem is a classic application of the Stack data structure. By using push and pop operations, we can efficiently determine whether an expression contains balanced parentheses. This is one of the most commonly asked stack-based programming questions in interviews and examinations because it demonstrates a practical real-world use of stacks.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.