Categories
Computer Science

Solving Problem: Balanced Parenthesis

Data Structures – Stacks

Problem Statement:

You are given a block of code or a string. Check for balanced parenthesis.

Example:

Sample Input1:

" # Example: Python code with unbalanced parentheses \
def add_numbers(a, b): \
return (a + b # Missing closing parenthesis \
# Calling the function \
result = add_numbers(5, 3) \
print('Result':, result) "

Expected Output1:

False

Sample Input2:

" # Example: Python code with unbalanced parentheses \
def add_numbers(a, b): \
return (a + b) # Closed parenthesis \
# Calling the function \
result = add_numbers(5, 3) \
print('Result':, result) "

Expected Output2:

True

Solution:

# Balanced parentheses
def is_balanced(s):
stack = []
mapping = {')':'(', ']':'[', '}':'{'}
for char in s:
if char in mapping.values():
stack.append(char)
elif char in mapping:
if not stack or stack.pop() != mapping[char]:
return False
return not stack
string1 = " # Example: Python code with unbalanced parentheses \
def add_numbers(a, b): \
return (a + b # Missing closing parenthesis \
# Calling the function \
result = add_numbers(5, 3) \
print('Result':, result) "
print(is_balanced(string1))

Output:

Priyanka B.'s avatar

By Priyanka B.

Hello and welcome to my little corner of internet!! I am a techie. I am very interested to discover and innovate new advances in science and technology. Blogging is one of my hobbies which I think is very useful for broadening my knowledge horizons and help me grow my skills. Apart from blogging I have also little taste in artistic skills and literature, which can keep my writing and posts tangy.

Whether you stumbled in by chance or came here on purpose, I hope you find something that sparks your curiosity or makes you think a little deeper. Thanks for stopping by!!

Leave a comment