Balanced Parenthesis Problem in Python

Understanding Balanced Parenthesis Problem

The balanced parenthesis problem involves checking whether a given string of brackets is balanced or not.

We will explore three different methods to solve this problem in Python.

Method 1: Using Stack

def is_balanced(expr):
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}
    for ch in expr:
        if ch in mapping.values():
            stack.append(ch)
        elif ch in mapping.keys():
            if not stack or stack.pop() != mapping[ch]:
                return False
    return not stack

expr = "{[()]}"
print("Balanced" if is_balanced(expr) else "Not Balanced")
            

Method 2: Using Counter

def is_balanced(expr):
    count = 0
    for ch in expr:
        if ch == '(':
            count += 1
        elif ch == ')':
            count -= 1
        if count < 0:
            return False
    return count == 0

expr = "(())"
print("Balanced" if is_balanced(expr) else "Not Balanced")
            

Method 3: Recursion

def check_balance(expr, index=0, count=0):
    if count < 0:
        return False
    if index == len(expr):
        return count == 0
    if expr[index] == '(':
        return check_balance(expr, index + 1, count + 1)
    if expr[index] == ')':
        return check_balance(expr, index + 1, count - 1)
    return check_balance(expr, index + 1, count)

expr = "((()))"
print("Balanced" if check_balance(expr) else "Not Balanced")
            
Top 100 Codes By Learn-for-free
Start Preparing Arraysform here👇

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

Find Largest Element in an Array: C C++ Java Python

Find Smallest Element in an Array: C C++ Java Python

Find the Smallest and Largest Element in an Array: C C++ Java Python

Find Second Smallest Element in an Array: C C++ Java Python

Calculate the Sum of Elements in an Array: C C++ Java Python

Reverse an Array: C C++ Java Python

Sort First Half in Ascending Order and Second Half in Descending: C C++ Java Python

Finding the Frequency of Elements in an Array: C C++ Java Python

Counting the Number of Even and Odd Elements in an Array: C C++ Java Python

Finding Maximum Product Sub-array in a Given Array: C C++ Java Python

Finding Arrays are Disjoint or Not: C C++ Java Python

Finding Equilibrium Index of an Array: C C++ Java Python

Rotation of Elements of Array - Left and Right: C C++ Java Python

Balanced Parenthesis Problem: C C++ Java Python