Valid Parentheses

easy

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.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Examples

Example 1

  • Input: s = "()"
  • Output: true

Example 2

  • Input: s = "()[]{}"
  • Output: true

Example 3

  • Input: s = "(]"
  • Output: false

Example 4

  • Input: s = "([])"
  • Output: true

Constraints

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

Approaches

Worked solution with intuition, algorithm, and verified code in C++, Java, Python, and Go.

Approach 1

Stack

Intuition

A stack is the perfect data structure for matching brackets because it follows a Last-In-First-Out (LIFO) order, which mirrors how nested brackets work -- the most recently opened bracket must be the first one closed. When we encounter an opening bracket, we push it onto the stack. When we encounter a closing bracket, we check if it matches the top of the stack (the most recent unmatched opening bracket). If it matches, we pop the stack and continue. If it does not match, or the stack is empty when we see a closing bracket, the string is invalid. At the end, the string is valid only if the stack is empty (all brackets matched).

Algorithm

  1. Create a mapping of closing brackets to their corresponding opening brackets for quick lookup.
  2. Initialize an empty stack.
  3. Iterate through each character in the string.
  4. If the character is an opening bracket ( '(', '[', '{' ), push it onto the stack.
  5. If the character is a closing bracket, check if the stack is non-empty and the top element matches the corresponding opening bracket.
  6. If it matches, pop the top of the stack. If it does not match or the stack is empty, return false.
  7. After processing all characters, return true if the stack is empty, false otherwise.
TimeO(n)SpaceO(n)

Code (C++ · Java · Python · Go)

C++17
class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        unordered_map<char, char> map = {
            {')', '('},
            {']', '['},
            {'}', '{'}
        };

        for (char c : s) {
            if (map.count(c)) {
                if (st.empty() || st.top() != map[c]) {
                    return false;
                }
                st.pop();
            } else {
                st.push(c);
            }
        }

        return st.empty();
    }
};
Java 21
class Solution {
    public boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        Map<Character, Character> map = Map.of(
            ')', '(',
            ']', '[',
            '}', '{'
        );

        for (char c : s.toCharArray()) {
            if (map.containsKey(c)) {
                if (stack.isEmpty() || !stack.peek().equals(map.get(c))) {
                    return false;
                }
                stack.pop();
            } else {
                stack.push(c);
            }
        }

        return stack.isEmpty();
    }
}
Python 3.12
def isValid(s: str) -> bool:
    stack = []
    mapping = {")": "(", "]": "[", "}": "{"}

    for char in s:
        if char in mapping:
            if not stack or stack[-1] != mapping[char]:
                return False
            stack.pop()
        else:
            stack.append(char)

    return len(stack) == 0
Go 1.26
func isValid(s string) bool {
    stack := []rune{}
    pairs := map[rune]rune{')': '(', '}': '{', ']': '['}
    for _, ch := range s {
        if ch == '(' || ch == '{' || ch == '[' {
            stack = append(stack, ch)
        } else {
            if len(stack) == 0 || stack[len(stack)-1] != pairs[ch] {
                return false
            }
            stack = stack[:len(stack)-1]
        }
    }
    return len(stack) == 0
}

Frequently asked questions

What is the optimal time complexity of Valid Parentheses?

The most efficient approach in this guide ("Stack") runs in O(n) time and uses O(n) extra space.

What pattern does Valid Parentheses use?

Valid Parentheses is a easy-level Stack problem involving String, Stack. Recognizing the pattern is half the work — see the intuition section above for how to spot it.

Which programming languages does this Ratta solution support?

Every approach above ships with verified, runnable solutions in C++, Java, Python, and Go. The starter templates in the workspace match the same four languages so you can practice in your interview language of choice.

Original problem: leetcode.com

Loading editor...
s=
"()"
true