Valid Parentheses Problem – Python

The task is to determine if a given string of parentheses is balanced. A string is considered balanced if every opening parenthesis has a corresponding closing parenthesis in the correct order. For example, the string “({[]})” is valid, while “({[)]}” is not.

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

# Example usage
print(is_balanced("({[]})"))  # True
print(is_balanced("({[)]}"))  # False

The function is_valid_parentheses takes a string s as input and returns a boolean indicating whether the parentheses in the string are balanced. Here is a breakdown of the code –

  1. Initialization: A stack is initialized to keep track of opening symbols, and a dictionary is created to define pairs of matching symbols.
  2. Iteration: The function iterates through each character in the input string.
  3. Push Opening Symbols: If the character is an opening symbol, it is pushed onto the stack.
  4. Check Closing Symbols: If the character is a closing symbol, the function checks if it matches the most recent opening symbol from the stack.
  5. Return Result: Finally, the function returns True if all symbols are balanced (i.e., the stack is empty) and False otherwise.