Valid Parentheses — LeetCode 20 Python Solution

EasyStackString
Problem
#20
Pattern
Stack
Reading time
2 min

The problem

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets.

Python solution

Python
class Solution:
    def isValid(self, s: str) -> bool:
        stk = []
        d = {'()', '[]', '{}'}
        for c in s:
            if c in '({[':
                stk.append(c)
            elif not stk or stk.pop() + c not in d:
                return False
        return not stk

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 20. Valid Parentheses is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 20. Valid Parentheses?
LeetCode 20. Valid Parentheses is rated Easy on LeetCode.
What is the time complexity of LeetCode 20. Valid Parentheses?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 20. Valid Parentheses?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 20. Valid Parentheses cover?
LeetCode 20. Valid Parentheses is tagged Stack and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview