Balanced Paranthesis Checker
Balanced Paranthesis Checker
YEAR 2025-26
A PROJECT REPORT OF
DATA STRUCTURE USING PYTHON (313306)
Submitted By
SY Artificial Intelligence
(2025-26)
1|Page
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION , MUMBAI
YEAR 2025-26
Certificate
This is to certify that
2|Page
Index
Sr. No. Content
1 Title Page
2 Problem Statement
3 Objectives
4 Apparatus / Software Requirements
5 Introduction to Theory
6 Methodology / Working Principle
7 Block Diagram / Flowchart
8 Algorithm / Code Implementation
9 Output / Result
10 Applications
11 Observations / Data Analysis
12 Advantages
13 Limitations
14 Future Scope
15 Conclusion
3|Page
1.Title of the project :-
Balanced Parentheses Checker (Using Stack)
i. Introduction to the topic :-
In today’s digital world, programming and software development rely heavily on writing
syntactically correct and logically structured code. One of the most common and important aspects
of syntax in programming languages involves the correct use of parentheses, brackets, and braces.
These symbols play a crucial role in defining the order of operations, function calls, conditional
statements, and code blocks. However, as programs grow in complexity, ensuring that every
opening bracket has a corresponding closing bracket becomes a challenging task. A single missing
or misplaced parenthesis can lead to syntax errors, logic errors, or even system failures. To
overcome this problem, a Balanced Parentheses Checker proves to be an effective and efficient
solution.
The project titled “Balanced Parentheses Checker (using Stack)” is based on the concept of data
structures, particularly the stack, which follows the Last In, First Out (LIFO) principle. This
property makes the stack an ideal choice for problems that involve matching pairs of symbols,
such as parentheses. The main idea is that whenever an opening bracket (like ‘(’, ‘{’, or ‘[’)
appears, it is pushed onto the stack, and whenever a closing bracket is encountered, the system
checks if it correctly matches the top element of the stack. If it matches, the top element is popped;
otherwise, the expression is declared unbalanced. At the end of the traversal, if the stack is empty,
it signifies that all parentheses are properly balanced.
This project not only provides a simple yet powerful way to verify the correctness of expressions
but also helps in understanding how stacks can be applied to solve real-world computational
problems. It demonstrates how dynamic memory and structured data handling can make problem-
solving more efficient. The concept of the Balanced Parentheses Checker is widely used in
compilers, interpreters, expression evaluators, and syntax analyzers, where proper nesting of
symbols is crucial.
The primary objective of this project is to design a system that can automatically check whether
the parentheses in a given expression are balanced or not using stack operations. Through this,
learners can gain deeper insight into stack implementation, function usage, and algorithmic
thinking. Thus, the project not only reinforces theoretical knowledge of data structures but also
enhances practical programming skills, logical reasoning, and error-handling abilities.
4|Page
ii. Importance and Practical Relevance
In the field of computer science and software development, ensuring the correctness and
consistency of expressions and code structures is of great importance. A small error such as a
missing parenthesis, brace, or bracket can cause an entire program to fail or behave unexpectedly.
This highlights the need for an efficient mechanism to verify the balanced use of parentheses in
mathematical expressions, programming code, and logical statements. The Balanced Parentheses
Checker serves as a fundamental tool to detect and prevent such errors, ensuring the syntactical
accuracy of code before execution.
The use of a stack data structure makes this project both conceptually and practically significant.
A stack operates on the Last In, First Out (LIFO) principle, which is perfectly suited for matching
and validating nested structures like parentheses. When an opening symbol appears, it is pushed
onto the stack, and when a closing symbol is encountered, it is matched with the top element of
the stack. This process continues until the entire expression is checked, making the system highly
efficient for syntax validation. Such stack-based checking forms the basis of compiler design,
expression parsing, and syntax validation used in almost every modern programming language.
In real-world applications, the logic of balanced parentheses checking extends far beyond just code
syntax. It is widely.
Conceptually, the checker works by scanning each symbol of an expression sequentially. When an
opening bracket (‘(’, ‘{’, ‘[’) is encountered, it is pushed onto the stack, and when a closing bracket
(‘)’, ‘}’, ‘]’) appears, the program checks the top of the stack to determine whether it matches the
corresponding opening symbol. If a mismatch occurs or the stack becomes empty prematurely, the
expression is identified as unbalanced. Once the entire expression has been processed, an empty
stack indicates that all parentheses are properly balanced. This logical process reinforces the
understanding of stack operations such as push, pop, peek, and isEmpty(), making it a strong
example of practical data structure utilization.
5|Page
From a broader perspective, this project provides a conceptual bridge between theoretical data
structures and their real-time applications. The same stack-based approach used here is employed
in various compiler and interpreter designs to check syntax correctness during code compilation.
It is also used in expression evaluation algorithms (such as infix to postfix conversion),
HTML/XML tag validation, and parsing arithmetic or logical expressions in programming
languages. Even modern text editors and IDEs use similar logic to highlight mismatched
parentheses or braces while coding.
For learners, implementing this project helps develop a deeper understanding of how abstract data
structures like stacks can be utilized to maintain order, structure, and accuracy in computational
logic. It also enhances problem-solving skills and algorithmic thinking, which are essential for
advanced concepts such as recursion, parsing, and memory management. Thus, the Balanced
Parentheses Checker not only demonstrates a clear conceptual understanding of stack operations
but also showcases their wide-ranging applications in both academic learning and professional
software development.
6|Page
2. Statement / Problem Statement :-
i. Understanding the Problem :-
In modern computing and programming environments, ensuring the correctness of code and
expressions is a fundamental requirement. One of the most common sources of logical and
syntactical errors in programming languages, mathematical expressions, and structured data
formats is the improper use of parentheses, brackets, and braces.
Parentheses are used to define scope, grouping, and order of operations — whether in
mathematical formulas, programming constructs, or markup languages such as HTML and XML.
However, when these symbols are not properly balanced (for example, when an opening bracket
has no corresponding closing bracket), it leads to errors that can cause program crashes, incorrect
calculations, or invalid document structures.
Manually verifying the balance of parentheses in complex expressions or large blocks of code is
time-consuming and error-prone. Even a single missing or misplaced bracket can disrupt the entire
logic of a program. For instance, in a large C or Java program, missing a closing brace (}) can
make debugging difficult and reduce productivity. Similarly, in mathematical computations or
compiler design, an unbalanced expression like ((a + b) * c can lead to syntax errors or incorrect
evaluations.
To address this problem, an automated and efficient method is required to verify whether a given
expression has properly balanced parentheses. The Balanced Parentheses Checker solves this issue
by using the Stack data structure, which operates on the principle of Last In, First Out (LIFO).
In this system, every time an opening symbol such as (, {, or [ appears, it is pushed onto the stack.
When a closing symbol ), }, or ] is encountered, it checks whether it matches the top element of
the stack. If it matches, the top element is popped; if not, the expression is deemed unbalanced. At
the end of the process, if the stack is empty, the expression is balanced; otherwise, it is not.
The stack-based approach provides a systematic, efficient, and reliable way to validate expressions
in real-time. It avoids manual inspection and guarantees correctness through an algorithmic
process.
This concept is widely used in compiler design, syntax validation, expression evaluation, and
parsing structured documents. Beyond practical applications, this project also serves as a valuable
educational tool for understanding the core working of stacks and their applications in real-world
problems.
7|Page
Therefore, the Balanced Parentheses Checker using Stack is an essential tool that demonstrates
both theoretical understanding and practical implementation of data structures. It highlights how
simple algorithms can solve real-world problems efficiently, making it a vital learning exercise for
students and an indispensable utility for programmers.
Traditional linear scanning methods without the use of appropriate data structures fail to efficiently
manage nested relationships. Therefore, there is a strong need for a system that can systematically
track the opening and closing of brackets in the correct order using an efficient, well-suited data
structure.
Problem Statement:
“To design and implement a Balanced Parentheses Checker using the concept of Stack data
structure that can efficiently determine whether the parentheses in a given expression are correctly
balanced and properly nested.”
This project focuses on developing a simple yet effective software tool that uses a Stack, a Last-
In-First-Out (LIFO) data structure, to solve the problem of parentheses matching. The stack allows
temporary storage of opening brackets and enables quick verification of corresponding closing
brackets, making it ideal for problems involving nested structure validation.
Accept input expressions containing different types of brackets: parentheses (), curly braces {},
and square brackets [].
Correctly identify whether the brackets are balanced and properly nested.
Handle both simple and complex expressions with multiple nested levels.
Use a Stack to push opening brackets and pop them when matching closing brackets are found.
Clearly demonstrate the practical use of stacks in parsing and validation tasks.
8|Page
By addressing these problems, the project demonstrates how abstract data structures like stacks
can be applied to real-world scenarios in programming and computer science. It bridges theoretical
learning with practical implementation, providing insight into how compilers, interpreters, and
various text editors ensure syntactic correctness. This foundational understanding also prepares
students for more advanced topics such as expression evaluation, syntax trees, and formal language
processing.
3.Objectives
Objective 1: To Develop an Efficient Parentheses Checking System
The primary goal of this project is to design and implement a program that efficiently verifies
whether the parentheses, brackets, and braces in a given expression are properly balanced. The
system should accurately detect any mismatched, missing, or extra symbols and display
appropriate results to the user.
This objective emphasizes building a logical and automated solution that eliminates human errors
commonly made while checking long and nested expressions manually. By doing so, the project
simplifies the process of syntax validation in mathematical formulas and programming codes. It
also provides a foundation for understanding how basic algorithms can be used to ensure
correctness and reliability in software systems.
In this project, each time an opening bracket (‘(’, ‘{’, ‘[’) is encountered, it is pushed onto the
stack. When a closing bracket (‘)’, ‘}’, ‘]’) appears, the program checks whether it matches the top
element of the stack and pops it if valid. This mechanism ensures that every opening symbol has
a correctly placed closing symbol, maintaining expression balance.
Through this objective, learners gain a practical understanding of stack operations like push, pop,
peek, and isEmpty(), and see how they can be applied to real-world programming problems such
as syntax checking, parsing, and compiler design.
9|Page
Objective 3: To Strengthen Understanding of Data Structures Using
Python
This project aims to bridge the gap between theoretical learning and practical application by
implementing the stack data structure using the Python programming language. Python’s
simplicity and readability make it an excellent choice for beginners to focus on algorithm design
and logic building without being hindered by complex syntax.
Students will learn how to create stack operations using lists or classes, understand how data is
managed dynamically in memory, and apply object-oriented programming principles to solve
logical problems. This objective enhances the learner’s capability to implement data structures in
real-world programming environments, improving both coding efficiency and conceptual
understanding.
This objective focuses on reducing human error and increasing efficiency in coding and
mathematical computation. The same concept can later be extended to develop syntax analyzers,
compilers, and interpreters, which rely on similar stack-based algorithms to ensure program
correctness before execution. The project, therefore, serves as a simplified model of how complex
systems handle syntax checking internally..
10 | P a g e
This objective encourages analytical thinking — understanding how data moves within a stack,
how conditional checks are performed, and how efficiency can be improved through algorithm
design. Ultimately, it builds a strong foundation for tackling advanced programming challenges
involving parsing, recursion, and expression evaluation.
❖ Software Requirements:
• Text Editor (Notepad++ / Sublime Text) for writing and editing code
• Version control systems like Git / GitHub for code management
• Online Python compilers (e.g., Repl.it, Google Colab) if IDE is not installed
• Documentation tools like Microsoft Word, Google Docs, or LaTeX for project
report preparation
12 | P a g e
5. Introduction to Theory
I. Introduction to Theory
In computer science, data structures are techniques for organizing, storing, and managing data
efficiently, enabling quick access, modification, and validation. Among the fundamental data
structures, a stack is a linear structure that follows the Last In, First Out (LIFO) principle. This
means the last element added to the stack is the first one to be removed. Stacks are widely used in
applications where order and nesting matter, such as expression evaluation, syntax parsing, and
function call management.
The Balanced Parentheses Checker is a practical application of the stack data structure. It
validates whether an expression contains correctly nested and matched parentheses (), braces {},
and brackets []. The system reads an expression symbol by symbol and uses stack operations to
ensure that every opening symbol has a corresponding closing symbol in the correct order.
Unlike manual checking, which is prone to human error and difficult for complex or deeply nested
expressions, a stack-based system handles this task efficiently. By dynamically pushing and
popping symbols, the program can manage multiple levels of nesting without confusion or the
need for extra memory management.
The main goal of using a stack is to validate expressions logically and systematically. Each opening
bracket is pushed onto the stack, and each closing bracket is compared against the top element of
the stack. If they match, the top element is popped, and the process continues until the end of the
expression. If the stack is empty at the end, the expression is balanced; otherwise, it is unbalanced.
This method ensures precise and error-free validation for both simple and complex expressions.
1. Stack Structure:
Stores only opening symbols ((, {, [).
2. Push Operation:
13 | P a g e
3. Pop Operation:
When a closing symbol is encountered, the program pops the top element of the stack and
checks if it matches the closing symbol.
If a closing symbol appears when the stack is empty, the expression is unbalanced.
5. End of Expression:
Using List:
append() → Push
pop () → Pop
[-1] → Peek
14 | P a g e
Using Class:
class Stack:
def _init_(self):
self.items = []
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return None
def peek(self):
if not self.is_empty():
return self.items[-1]
return None
def is_empty(self):
return len(self.items) == 0
15 | P a g e
iv . Applications and Advantages
Applications:
• Validating code syntax in compilers and interpreters.
Advantages:
• Efficient handling of nested expressions of any depth.
• Eliminates human error in manual validation.
• Simple implementation using basic stack operations.
• Provides a foundation for understanding expression evaluation and compiler design.
5. Methodology / Working
The methodology section explains how the Balanced Parentheses Checker (using Stack)
project is designed, implemented, and executed. It describes the logical flow of the
program, how the stack is used to manage symbols dynamically, and the stepwise working
principle of verifying balanced parentheses in an expression.
16 | P a g e
The project is implemented in Python using a stack-based approach, which follows the Last
In, First Out (LIFO) principle. Each opening symbol in an expression is pushed onto the
stack, and each closing symbol is compared with the top element of the stack for validation.
This approach ensures correct handling of nested and sequential parentheses without
human error.
• The first step is to design the stack structure and define operations:
• Stack Structure:
• Uses Python list or class-based stack.
• Stores only opening symbols: (, {, [.
• Maintains LIFO order for proper matching.
❖ Implementation Phase
The implementation involves creating a stack structure and writing logic to check for
balanced symbols.
➢ Stack Implementation in Python:
17 | P a g e
class Stack:
def _init_(self):
self.items = []
def pop(self):
if not self.is_empty():
return self.items.pop()
return None
def peek(self):
if not self.is_empty():
return self.items[-1]
return None
➢ Algorithm Steps:
Working Principle:
Advantages of Methodology
• Efficiently handles nested and complex expressions.
• Reduces human error in manual checking.
19 | P a g e
• Provides hands-on understanding of stack operations.
• Forms the foundation for compiler design, expression evaluation, and syntax
parsing.
• Scalable for expressions of any length or depth.
class Node:
def __init__(self, roll, name, branch, marks):
self.roll = roll
self.name = name
self.branch = branch
self.marks = marks
self.next = None
Implementation Steps:
• Insertion: Create a new node → If list is empty, make it head → Else, traverse and link
new node at correct position.
• Deletion: Traverse the list to find the node → Update previous node’s next to skip the
deleted node → Delete node from memory.
• Search: Start at head → Compare each node’s roll number → Display record if found.
• Update: Search node → Modify required fields.
• Display: Traverse from head → Print each node’s details.
Working Principle:
20 | P a g e
Python handles memory allocation automatically. Each node exists as a separate object, and
references link nodes together to form the chain.
Input Expression (String): The sequence of characters (including various types of brackets: {},
[], ()) to be checked.
Mapping (Optional): A way to quickly identify corresponding opening and closing brackets (e.g.,
{ matches }).
Push to Stack: When an opening bracket ((, {, [) is encountered, push it onto the stack.
Pop from Stack: When a closing bracket (), }, ]) is encountered, pop the top element from the
stack.
Match Check: After popping, verify if the popped opening bracket correctly matches the
encountered closing bracket.
Empty Stack Check: Check if the stack is empty at various points (e.g., when a closing bracket is
found but no opening bracket is on the stack, or at the end of the expression).
Working Principle:
Initialize an empty stack.
21 | P a g e
Check if the stack is empty. If it is, the expression is immediately unbalanced (no opening bracket
to match).
If not empty, pop the top element (which should be an opening bracket) from the stack.
Compare the popped opening bracket with the current closing bracket. If they don't form a valid
pair (e.g., ( and ]), the expression is unbalanced.
If the stack is empty, all opening brackets were successfully matched with their corresponding
closing brackets, and the expression is balanced.
If the stack is not empty, there are unmatched opening brackets, and the expression is unbalanced.
This design ensures dynamic processing, flexibility, and efficient operation for checking bracket
balance.
Implementation Structure:
stack = []
# A dictionary for quick lookup of matching brackets
# Define sets for opening and closing brackets for easy checking
22 | P a g e
# If it's an opening bracket, push it onto the stack
stack.append(char)
return False
top_element = stack.pop()
# Check if the popped opening bracket matches the current closing bracket
if bracket_map[char] != top_element:
return False
Iterate Characters: Loop through each character (char) in the input expression.
Handle Opening Brackets: If char is an opening bracket ((, {, [), push char onto the stack.
Pop Element: Remove the last element added to the stack (the most recent opening bracket).
Check Match: Use bracket_map to see if the popped opening bracket is the correct match for the
current char. If not, return False (unbalanced).
Final Check: After the loop finishes, check if the stack is empty. If it is, all brackets were matched,
return True (balanced). Otherwise, there are unmatched opening brackets, return False.
Working Principle:
Python's lists inherently support stack operations (append for push, pop for pop). The logic relies
on the LIFO principle: the most recently opened bracket must be the first one closed. By tracking
23 | P a g e
opening brackets and immediately verifying closing brackets against the stack's top, the system
efficiently detects mismatches or unclosed brackets.
Working Principle:
This direct interaction provides immediate feedback on the balance of the input expression.
The character-by-character traversal and stack manipulation ensure that the operation is
performed sequentially and logically. The stack dynamically grows and shrinks based on
the input, reflecting the real-time matching process.
Data Flow Diagram (Conceptual):
User Input (Expression String) → check_balanced_parentheses Function → Stack
Manipulation (Push/Pop/Match) → Boolean Result (True/False) → Output Display
24 | P a g e
V . Testing, Validation, and Advantages
Advantages of Methodology:
The use of a stack for the Balanced Parentheses Checker offers several significant advantages:
25 | P a g e
• Foundation for Advanced Parsing: This methodology provides a fundamental
understanding of how stacks are used in more complex parsing tasks, such as compilers,
interpreters, and syntax validators, making it a crucial concept for computer science
education.
• Low Memory Footprint: The memory usage is proportional to the maximum nesting
depth of the brackets, not the total length of the expression, making it memory-efficient for
deeply nested but short expressions.
26 | P a g e
Explanation of Block Diagram:
1. Start & Initialize: Begin the process by initializing an empty stack.
2. Read Input: Get the expression string that needs to be checked.
3. Process Each Character (Loop): Go through the expression character by
character:
➢ If Opening Bracket: Push the character onto the stack.
➢ If Closing Bracket:
27 | P a g e
o Check if the stack is empty. If yes, it's immediately Unbalanced.
o If not empty, pop the top element from the stack.
o Check if the popped element (opening bracket) correctly matches the
current closing bracket. If no, it's immediately Unbalanced.
o If Other Character: Ignore and continue to the next character.
4 . After Loop Ends (Final Check): Once all characters are processed:
o If Stack is Empty: The expression is Balanced.
o If Stack is Not Empty: The expression is Unbalanced (unmatched
opening brackets remain).
5. End: The process concludes with the result.
II. Flowchart
28 | P a g e
Explanation of Flowchart Diagram:
1. Start & Initialize: Begin the process by initializing an empty stack.
2. Read Input: Get the expression string that needs to be checked.
3. Process Each Character (Loop): Go through the expression character by
character:
➢ If Opening Bracket: Push the character onto the stack.
➢ If Closing Bracket:
4 . After Loop Ends (Final Check): Once all characters are processed:
o If Stack is Empty: The expression is Balanced.
o If Stack is Not Empty: The expression is Unbalanced (unmatched
opening brackets remain).
5. End: The process concludes with the result.
7. Code :-
#------------------------------------------------------------------
Title : Balanced Parentheses Checker (Using Stack)
# Author : [Your Name]
# Language : Python
# Description: Program to check whether parentheses in an expression
# are balanced using Stack data structure.
#------------------------------------------------------------------
#-------------------------------
# Stack Class Implementation
#-------------------------------
class Stack:
def _init_(self):
"""Initialize an empty stack."""
self.stack = []
29 | P a g e
def is_empty(self):
"""Check whether the stack is empty."""
return len(self.stack) == 0
def pop(self):
"""Pop an item from the stack."""
if not self.is_empty():
popped = self.stack.pop()
print(f"→ Popped '{popped}' from stack. Current Stack: {self.stack}")
return popped
else:
print("⚠ Stack Underflow! Tried to pop from an empty stack.")
return None
def peek(self):
"""Return the top element of the stack."""
if not self.is_empty():
return self.stack[-1]
return None
def size(self):
"""Return the size of the stack."""
return len(self.stack)
def display(self):
"""Display stack content."""
print("Current Stack:", self.stack)
#-------------------------------
# Balanced Parentheses Function
#-------------------------------
def is_balanced(expression):
"""Check whether an expression has balanced parentheses."""
stack = Stack()
opening = "([{"
30 | P a g e
closing = ")]}"
print("\nChecking Expression:", expression)
# Final validation
if stack.is_empty():
print(" Expression is Balanced.\n")
return True
else:
print(" Unmatched brackets remain in stack:", stack.stack)
print(" Expression is NOT Balanced.\n")
return False
#-------------------------------
# Main Program (Menu Driven)
#-------------------------------
def main():
while True:
print("\n===== Balanced Parentheses Checker =====")
print("1. Check Single Expression")
print("2. Check Multiple Expressions")
print("3. Exit")
31 | P a g e
choice = input("Enter your choice (1-3): ")
if choice == '1':
expression = input("Enter an expression: ")
is_balanced(expression)
else:
print("Invalid choice! Please try again.")
#-------------------------------
# Run Program
#-------------------------------
if _name_ == "_main_":
main()
32 | P a g e
1.
2.
4.
5.
33 | P a g e
6.
7.
8.
34 | P a g e
9.
8. Applications
Use Case:
Before an expression is evaluated by a calculator or an interpreter, the program must ensure that
the parentheses are properly matched to avoid misinterpretation or runtime errors.
35 | P a g e
Evaluating arithmetic expressions in calculators.
When a programmer types an opening bracket, the editor highlights the matching closing
bracket. This functionality relies on stack-based algorithms to dynamically track balanced pairs.
Impact:
Improves coding accuracy.
Many data formats such as JSON, XML, and HTML rely on properly nested and matched tags or
braces.
Balanced parentheses checking logic can be extended to verify whether all tags and brackets are
correctly opened and closed. This ensures that structured data files are well-formed before being
processed by parsers or web applications.
Example:
36 | P a g e
5. Compiler Intermediate Code Generation
Unbalanced expressions can cause incorrect symbol table entries, faulty intermediate code, and
misaligned execution blocks. Stack-based parentheses checking ensures that code translation
remains accurate and consistent.
Example:
Text processors and editors that support auto-formatting or syntax highlighting depend on balanced
symbol checking.
When a user types an opening bracket or quotation mark, the system automatically checks for
matching pairs to assist in writing structured content such as LaTeX documents, Markdown, or
JSON files.
Use Case:
Detecting missing symbols in structured documents.
Stack-based algorithms for infix to postfix conversion depend on the correct pairing of brackets to
maintain operator precedence and operand grouping.
37 | P a g e
Example:
Languages like SQL, JavaScript, and Python use parentheses and braces for query grouping and
function calls.
Before execution, interpreters check for balanced parentheses to avoid syntax errors or
misinterpretation of code logic.
Example:
Ensuring parentheses match in SQL queries like SELECT * FROM table WHERE (a > 5 AND (b
< 10));.
This project serves as an excellent learning tool for students studying Data Structures and
Algorithms.
It helps in understanding the practical application of the Stack (LIFO) principle and how it can be
applied to solve real-world problems efficiently.
Learning Outcomes:
38 | P a g e
10. Web Development and Front-end Validation
In web applications, especially those accepting user-generated formulas or code snippets (like
online editors or calculators), parentheses checking ensures data integrity before submission.
It prevents runtime errors and improves reliability by validating the structure of user input.
Example:
9. Data Observations
1. Objective
To observe and analyze the working of the Balanced Parentheses Checker program that
uses the Stack data structure for verifying the correctness of parentheses, brackets, and
braces in a given expression.
2. Principle / Concept
The stack follows the LIFO (Last In, First Out) principle.
Every closing symbol — ), }, ] — causes a pop operation, and the popped element is
compared.
If at any time a mismatch occurs, or a closing bracket appears without a matching opening
one, the expression is Not Balanced.
At the end, if the stack is empty, the expression is Balanced; otherwise, it’s Not Balanced.
39 | P a g e
3. Tools / Software Used
Programming Language: Python 3.x
Type Description
Input Expression containing parentheses (), curly braces {}, and square brackets [] (may
include operands, operators, etc.)
Output Message displaying whether the given expression is Balanced or Not Balanced
40 | P a g e
12 {a+[b*(c+d)]-e} Balanced Balanced Correct use of nested brackets
Complex multiple balanced
13 [()]{}{[()()]()} Balanced Balanced sequences
14 [({})](] Not Balanced Not Balanced Wrong closing bracket at end
15 (((()))) Balanced Balanced Deep nesting validated
16 ([A+B]*{C+D) Not Balanced Not Balanced Missing closing bracket
{[(A+B)*(C/D)] Complex expression checked
17 -(E+F)} Balanced Balanced correctly
18 ((A+B)*(C+D)] Not Balanced Not Balanced Mismatch detected
19 (Empty Input) Balanced Balanced No brackets → Balanced
20 {} Balanced Balanced Simple balanced case
Initial Stack: []
1 { Push {
2 [ Push {[
3 ( Push {[(
4 ) Pop (matched () {[
5 ] Pop (matched [) {
6 } Pop (matched {) [] (empty)
7. Observational Analysis
1. The stack correctly stores and removes symbols in LIFO order.
2. Each opening symbol is matched with its respective closing symbol.
3. Invalid or mismatched brackets are detected instantly.
4. Non-bracket characters (like A, +, *, /) are ignored safely.
41 | P a g e
6. If any opening remains in stack → expression is Not Balanced.
9. The program handles all types of brackets — (), {}, and [].
10. Expressions with multiple independent bracket sets are checked correctly.
12. Works correctly for empty strings or no-bracket expressions (considered balanced).
15. Suitable for evaluating arithmetic, logical, or code expressions for structural
correctness
• Or simply:
• Start → Input Expression → Initialize Stack → For each Character: Push / Pop →
Check Stack → Balanced / Not Balanced → End
9. Observation Summary
42 | P a g e
10. Inference / Result
It operates in O(n) time, where n is the length of the input expression. Each character is
checked exactly once, ensuring fast execution.
43 | P a g e
3. Reliable Error Detection
The program accurately detects missing, mismatched, or misplaced brackets, helping
identify syntax or logical errors in code or expressions.
44 | P a g e
10. Real-Time Validation
It can be integrated into text editors or IDEs to instantly highlight unbalanced
brackets while typing code.
It can easily be adapted for other forms of bracket checking such as < >, XML/HTML tags,
or even parentheses in natural language processing.
Logical and Structured Approach
The algorithm enforces a systematic checking method that ensures all open brackets are
matched correctly before closing.
45 | P a g e
18. High Accuracy
The stack ensures no unmatched or misordered parentheses escape detection — offering
100% accuracy for valid input strings.
Since each operation is predictable (push or pop), debugging the logic or tracing the stack
behavior is straightforward.
Compilers use the same logic for block validation in languages like C, Java, and Python —
especially for {} and indentation checks.
It works with variables, operators, and constants, not just plain brackets — suitable for
evaluating algebraic and logical formulas.
Though implemented in Python, the same logic can be easily converted to Java, C++, or C
without much modification.
When integrated with an input system, the algorithm can immediately indicate errors as
users type expressions, improving learning or development productivity.
46 | P a g e
24. Robust Against Incorrect Input
It safely handles invalid or incomplete expressions (like missing closing brackets) without
crashing, demonstrating good error handling.
Used in:
• This means the search operation has linear time complexity O(n).
• For a small number of students, this is acceptable, but for large datasets, searching can
become slow.
Example:
Searching for Roll No 500 in a list of 1000 students requires traversing up to 1000 nodes.
2. No Random Access
• Unlike arrays or databases, a linked list does not support direct access to a specific node.
• To access the 10th student, you must start at the head and traverse 9 nodes first.
47 | P a g e
Impact:
This limits performance when frequent random access is required.
• The pointer consumes extra memory compared to storing only the data.
Observation:
For small datasets, this is negligible, but for large-scale student records, the additional memory
can add up.
• Reverse operations, like printing records from the last student to the first, require extra
steps or additional data structures.
Example:
Displaying students in reverse order would require either recursion or creating a temporary stack.
Impact:
This limits the system’s use for long-term record-keeping unless file handling or database
integration is added.
Example:
Deleting Roll No 950 in a list of 1000 students requires traversing nearly the entire list.
Observation:
For detailed analysis, manual calculations or extra code is needed.
9. No Multi-User Access
• The system is designed for single-user operation.
Impact:
Not suitable for large institutions without implementing a client-server or web-based solution.
Example:
Entering a string instead of a numeric value for Marks may crash the program unless additional
checks are added.
49 | P a g e
11. Lack of Advanced Features
• Features such as sorting, filtering, or searching by multiple fields are not included.
Observation:
Advanced database features like queries or joins are not possible in this in-memory linked list
system.
• Anyone who opens the program can access or modify student records.
• This makes the system less secure, especially when used in shared environments.
• For example, entering a string instead of a number in marks or roll number may cause an
error.
• Adding proper input validation would improve the reliability and accuracy of the data.
51 | P a g e
12.Future Scope
The Balanced Parentheses Checker using Stack is a simple yet powerful program that lays the
foundation for various advanced computational and real-world applications. Although it efficiently
verifies whether parentheses are balanced in expressions, there is significant potential for
improvement
3. Auto-Correction Feature
A future update can automatically insert or suggest missing parentheses,
helping users quickly fix syntax issues without manual debugging.
52 | P a g e
4. Support for Additional Symbols
Apart from (), {}, and [], the checker can be expanded to include angle
brackets < > and custom delimiters used in different programming
languages.
6. GUI-Based Implementation
A Graphical User Interface (GUI) using libraries like Tkinter, PyQt, or
can make the system more interactive and user-friendly.
7. Web-Based Application
The checker can be converted into an online tool using Flask or Django,
allowing users to validate code snippets directly through a web browser.
53 | P a g e
9. Real-Time Bracket Matching Visualization
An interactive interface can visually display how the stack operates
showing which brackets are pushed and popped in real-time for
educational purposes.
54 | P a g e
Conclusion
The Balanced Parentheses Checker using Stack project successfully demonstrates the
practical application of the stack data structure in solving real-world problems related to
expression validation and syntax checking.
By using the Last-In-First-Out (LIFO) principle, the algorithm efficiently checks whether
every opening parenthesis in a given expression has a corresponding and correctly placed
closing parenthesis.
The implementation in Python showcases how a simple yet powerful concept like stacks can
ensure logical correctness, structural balance, and syntactical accuracy of expressions used
in mathematics and programming. The project validates various types of brackets — (), {},
and [] — and accurately identifies mismatched, missing, or misplaced parentheses in both
simple and complex expressions.
Through testing and analysis, the system proved to be reliable, accurate, and efficient,
operating with a time complexity of O(n) and minimal memory requirements. The
algorithm not only serves as a strong foundational example for understanding stack
operations but also provides a practical framework for extending functionality into more
advanced systems such as compiler syntax checkers, HTML/XML tag validators, and
expression parsers.
This project reinforces the importance of data structures and algorithms in computer
science, particularly how abstract concepts like stacks can be applied to real-life software
development challenges.
It provides a solid base for students and developers to explore deeper areas like compiler
design, expression evaluation, and programming language parsing.
55 | P a g e
13.References
i. Prof. S.A.Purkar mam (DSP)
ii. Textbook of Data structure using python (313306)
iv. Microsoft edge/Google
v. Singly Linked List in Pythonhttps://www.geeksforgeeks.org/linked-
list-in-python/
vi. https://chatgpt.com/
vii. https://gemini.com/
56 | P a g e