Math Fundamentals18 sections · 814 units
Open in Course

Valid Parentheses - Implementation

The code

Here's the complete solution:


function isValid(s)
    stack := empty stack
    for each char in s
        if char is '(' or '[' or '{' then
            stack.push(char)
        else
            if stack.isEmpty() then
                return false
            top := stack.pop()
            if (char = ')' and top  '(') or
               (char = ']' and top  '[') or
               (char = '}' and top  '{') then
                return false
    return stack.isEmpty()

Notice the boolean checks: stack.isEmpty() prevents popping from an empty stack. The OR conditions check if the bracket types mismatch. Both use boolean logic to validate structure.