Logo for ammarahmed.ca
Easy
Dec 22, 2025
#stack

20. Valid Parentheses

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
    1. Open brackets must be closed in the correct order.
      1. Every close bracket has a corresponding open bracket of the same type.

        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

        • 1 <= s.length <= 104
          • s consists of parentheses only '()[]{}'.

            Constraints:

            Notes

            • Intuition: Every opening bracket should eventually have a closing bracket that comes after it.
              • Implementation: Use a stack and a map that maps opening brackets to closing, when seeing an opening bracket, push the closing bracket to the stack, When seeing a closing bracket, check the top of the stack, if its the same, pop and keep going, otherwise return False.
                • Edge-cases: At the end, check the stack should be empty (unclosed brackets at the end). Also check if the stack is empty on seeing a closing bracket, return False there was no corresponding open.
                  • Complexity: Time O(n), Space O(n) (stack)

                    Solution

                    1 2class Solution: 3 def isValid(self, s: str) -> bool: 4 map = { 5 "(": ")", 6 "{": "}", 7 "[": ']', 8 } 9 stack = [] 10 for c in s: 11 if c in map: 12 # opening bracket 13 stack.append(map[c]) 14 else: 15 if len(stack) == 0 or stack[-1] != c: 16 return False 17 stack.pop() 18 19 20 return len(stack) == 0 21 22 23 24 25if __name__ == "__main__": 26 # Include one-off tests here or debugging logic that can be run by running this file 27 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 28 solution = Solution() 29