Member-only story

Parenthesis Checker

Paresh Krishna Sharma
3 min readJul 10, 2023

--

Validating Expression Pairs and Order in an Expression String

In programming, it is often necessary to examine whether the pairs and order of parentheses, brackets, and braces are correct in an expression. This article explores a solution to determine the correctness of expression pairs and order using a simple algorithm. We will provide a code implementation, analyze its time and space complexity, and discuss its applications.

Example of Parenthesis Checker

Algorithm

To examine the correctness of expression pairs and order, we can utilize a stack data structure. The algorithm follows these steps:

  1. Create an empty stack.
  2. Traverse the expression string from left to right.
  3. For each character in the expression:
    — If the character is an opening bracket (i.e., ‘(‘, ‘{‘, or ‘[‘), push it onto the stack.
    — If the character is a closing bracket (i.e., ‘)’, ‘}’, or ‘]’):
    — If the stack is empty, return false, as there is no corresponding opening bracket.
    — Pop the topmost element from the stack.
    — If the popped opening bracket does not match the current closing bracket, return false.
  4. After the traversal, if the stack is not empty, return false, as there are unclosed opening brackets.
  5. If the stack is empty after the traversal, return true, indicating that all the…

--

--

Paresh Krishna Sharma
Paresh Krishna Sharma

Written by Paresh Krishna Sharma

Unleashing the Power of Code, Data, and Creativity ✨ | Software Engineer at Microsoft | LinkedIn : www.linkedin.com/in/itsparesh

No responses yet