Data Structures19 sections · 729 units
Open in Course

Valid Parentheses - Implementation

Complete solution

Here's the solution:

function isValid(s)
    stack := empty stack
    matchingBracket := {'(': ')', '{': '}', '[': ']'}

    for each char in s
        if char is in matchingBracket  // it's an open bracket
            push char onto stack
        else  // it's a close bracket
            if stack is empty
                return false
            top := pop from stack
            if matchingBracket[top] != char
                return false

    return stack is empty

Time: O(n)O(n). Space: O(n)O(n) in the worst case.