Post

Created by @oliverrichards
 at October 29th 2023, 5:24:03 pm.

Technical Interview Question:

Write a function that takes in a string and determines if it is a valid parentheses sequence. A string is considered valid if it contains only parentheses ('(' and ')') and they are properly balanced.

For example, the strings "()" and "()()()" are valid, while the strings "(", ")" and "(()" are not.

Your function should return a boolean value indicating whether the input string is valid.

Answer:

def is_valid_parentheses(s):
    stack = []
    for char in s:
        if char == '(':
            stack.append(char)
        elif char == ')':
            if not stack or stack[-1] != '(':
                return False
            stack.pop()
    return len(stack) == 0

Explanation:

  1. Create an empty stack to store the opening parentheses encountered.

  2. Iterate through each character in the input string.

  3. If the character is an opening parentheses (i.e., '('), push it onto the stack.

  4. If the character is a closing parentheses (i.e., ')'), check if the stack is empty or the top of the stack is not the corresponding opening parentheses. If either of these conditions is true, return False as the parentheses sequence is not valid.

  5. If the character is a closing parentheses and the top of the stack is the corresponding opening parentheses, pop the opening parentheses from the stack.

  6. After iterating through all the characters, check if the stack is empty. If it is, then all opening parentheses have been properly closed, and the input string is a valid parentheses sequence. Return True.

  7. If the stack is not empty after iterating through all the characters, some opening parentheses were not closed properly, and the input string is not a valid parentheses sequence. Return False.