Skip to content

Latest commit

Β 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Β 
Β 
Β 
Β 

README.md

πŸ—‚ Data Structures & Algorithms Example: Stack & Balanced Parentheses

This Python script demonstrates the use of the Stack data structure to check balanced parentheses, brackets, and braces in an expression.
It’s a classic Data Structures & Algorithms (DSA) problem used in programming, interviews, and real-world parsing tasks.


πŸš€ Features

  • βœ… Implements a custom Stack class in Python
  • βœ… Checks for balanced parentheses, brackets, and braces
  • βœ… Handles nested and complex expressions
  • βœ… Supports expressions with other characters (letters, numbers, operators)
  • βœ… Easy to extend for other parsing problems

πŸ“¦ Requirements

  • Python 3.x

No additional libraries are required as the implementation uses core Python.


βš™ How It Works

  1. Stack Implementation

    • push(item) β†’ Adds element to top
    • pop() β†’ Removes and returns top element
    • peek() β†’ Returns top element without removing
    • is_empty() β†’ Checks if stack is empty
  2. Balanced Parentheses Algorithm

    • Traverse each character of the expression
    • Push opening symbols (, [, { onto the stack
    • On closing symbols ), ], }, check if the top of the stack matches
    • If mismatch or leftover elements β†’ expression is not balanced
    • Otherwise β†’ balanced

πŸ”§ Example Usage

print(is_balanced("()"))               # True
print(is_balanced("([)]"))             # False
print(is_balanced("((()))[{}]"))       # True
print(is_balanced("((()))[{}]]"))      # False
print(is_balanced("a + (b * c) - {d / [e + f]}")) # True
print(is_balanced("((a + b) * (c - d)"))  # False

πŸ“Š Complexity Analysis

  • Time Complexity: O(n) β†’ n = length of expression

  • Space Complexity: O(n) β†’ Worst-case stack size (all opening symbols)


πŸ’‘ Why This Is Useful

  • Core DSA concept: Stack
  • Common in parsing, compiler design, expression evaluation
  • Often asked in technical interviews
  • Foundation for more advanced algorithms like infix-to-postfix conversion

πŸ›  Extending the Script

  • Add support for custom symbols
  • Integrate into expression evaluators or mini calculators
  • Visualize stack operations for educational purposes
  • Combine with queues or trees for complex parsing algorithms