--- title: '20. Valid Parentheses' description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid icon: dot topics: - { name: "String", slug: "string" } - { name: "Stack", slug: "stack" } - { name: "Bracket Sequences", slug: "bracket-sequences" } video: "WTzjTskDFMg" issue: "https://github.com/prdlk/leetcode/issues/67" companies: - { name: "BlackRock", period: "Thirty Days", frequency: 100 } - { name: "Microsoft", period: "Thirty Days", frequency: 67.9 } - { name: "Amazon", period: "Thirty Days", frequency: 61.3 } - { name: "Google", period: "Thirty Days", frequency: 42.3 } - { name: "Accolite", period: "Three Months", frequency: 100 } - { name: "Intuit", period: "Three Months", frequency: 73.2 } - { name: "Bloomberg", period: "Three Months", frequency: 68.3 } - { name: "Meta", period: "Three Months", frequency: 65.3 } - { name: "tcs", period: "Three Months", frequency: 57.2 } - { name: "Autodesk", period: "Six Months", frequency: 100 } - { name: "Criteo", period: "Six Months", frequency: 100 } - { name: "Odoo", period: "Six Months", frequency: 100 } - { name: "Tripadvisor", period: "Six Months", frequency: 100 } - { name: "Virtu Financial", period: "Six Months", frequency: 100 } - { name: "IBM", period: "Six Months", frequency: 91.1 } - { name: "Epic Systems", period: "Six Months", frequency: 89.6 } - { name: "LinkedIn", period: "Six Months", frequency: 85.6 } sidebar: label: 'Valid Parentheses' badge: 'Easy' --- ### Example 1: - Input: `s = "()"` - Output: `true` ### Example 2: - Input: `s = "()[]{}"` - Output: `true` ### Example 3: - Input: `s = "(]"` - Output: `false` ### Example 4: - Input: `s = "([])"` - Output: `true` ### Example 5: - Input: `s = "([)]"` - Output: `false` ### Constraints: - `1 <= s.length <= 10^4` - `s` consists of parentheses only '()[]{}'. ## Approach ```mermaid flowchart TD S(["isValid(s)"]) --> I["stack = [], pairs = closer to opener"] I --> L{"more char c?"} L -- no --> Z{"stack empty?"} Z -- yes --> T(["return True"]) Z -- no --> U(["return False — unclosed openers left"]) L -- yes --> Q{"c is a closer?"} Q -- no --> A["stack.append(c) — it is an opener"] A --> L Q -- yes --> M{"stack non-empty and pairs[c] == stack[-1]?"} M -- yes --> P["stack.pop() — matched"] P --> L M -- no --> F(["return False — mismatch"]) ``` ## Solution ```py class Solution: def isValid(self, s: str) -> bool: stack = [] pairs = {")": "(", "]": "[", "}": "{"} for c in s: if c in pairs: if stack and pairs[c] == stack[-1]: stack.pop() else: return False else: stack.append(c) return True if not stack else False ```