KatInterview

20. Valid Parentheses

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if a string of parentheses is "valid". A string is valid if all opening brackets are closed by the same type of bracket, in the correct order. This implies a Last-In, First-Out (LIFO) order of operations for matching brackets. For instance, in ({[]}), the last opening bracket [ is the first one to be closed by ]. This LIFO behavior is a classic signal to use a stack data structure.

Solution

Valid Parentheses in Python

class Solution:
    def isValid(self, s: str) -> bool:
        # The stack will store the opening brackets.
        stack = []

        # A mapping of closing brackets to their corresponding opening brackets.
        mappings = {")": "(", "]": "[", "}": "{"}

        # Iterate through each character in the string.
        for char in s:
            # If the character is a closing bracket.
            if char in mappings:
                # Check if the stack is empty. If it is, we have a closing bracket with no opener.
                # Also check if the top of the stack is the matching opening bracket.
                # If stack is empty, `stack.pop()` would error. So we assign a dummy value '#' to top_element.
                top_element = stack.pop() if stack else '#'
                if mappings[char] != top_element:
                    return False
            else:
                # If it's an opening bracket, push it onto the stack.
                stack.append(char)
        
        # If the stack is empty, it means all brackets were matched correctly.
        # A non-empty stack means there are unclosed opening brackets.
        return not stack

Valid Parentheses in Java

import java.util.Deque;
import java.util.ArrayDeque;
import java.util.Map;
import java.util.HashMap;

class Solution {
    public boolean isValid(String s) {
        // Use a stack (ArrayDeque is a good implementation for a stack).
        Deque<Character> stack = new ArrayDeque<>();

        // A map to store mappings of closing to opening brackets.
        Map<Character, Character> map = new HashMap<>();
        map.put(')', '(');
        map.put(']', '[');
        map.put('}', '{');

        // Iterate over each character in the string.
        for (char c : s.toCharArray()) {
            // If the character is a closing bracket.
            if (map.containsKey(c)) {
                // If the stack is empty, there's no matching opening bracket.
                if (stack.isEmpty()) {
                    return false;
                }
                // Pop the top of the stack.
                char topElement = stack.pop();
                // If the popped element is not the corresponding opening bracket, the string is invalid.
                if (topElement != map.get(c)) {
                    return false;
                }
            } else {
                // If it's an opening bracket, push it onto the stack.
                stack.push(c);
            }
        }

        // If the stack is empty, all opening brackets have been closed. Otherwise, it's invalid.
        return stack.isEmpty();
    }
}

Valid Parentheses in C++

class Solution {
public:
    bool isValid(string s) {
        // Use a stack to keep track of opening brackets.
        std::stack<char> st;

        // A map to hold the matching pairs.
        std::unordered_map<char, char> map = {
            {')', '('},
            {']', '['},
            {'}', '{'}
        };

        // Iterate through each character in the string.
        for (char c : s) {
            // If the character is a closing bracket.
            if (map.count(c)) {
                // If the stack is empty, there's no matching opening bracket.
                // Or if the top of the stack is not the matching opening bracket.
                if (st.empty() || st.top() != map[c]) {
                    return false;
                }
                // It's a match, pop the opening bracket from the stack.
                st.pop();
            } else {
                // It's an opening bracket, push it onto the stack.
                st.push(c);
            }
        }

        // If the stack is empty, all brackets were matched correctly.
        // Otherwise, there are unmatched opening brackets.
        return st.empty();
    }
};

Valid Parentheses in TypeScript

function isValid(s: string): boolean {
    // The stack will store the opening brackets.
    const stack: string[] = [];

    // A mapping of closing brackets to their corresponding opening brackets.
    const map: { [key: string]: string } = {
        ")": "(",
        "]": "[",
        "}": "{",
    };

    // Iterate through each character in the string.
    for (let i = 0; i < s.length; i++) {
        const char = s[i];

        // If the character is a closing bracket.
        if (map[char]) {
            // If the stack is empty or the top of the stack is not the matching opening bracket,
            // the string is invalid.
            if (stack.length === 0 || stack[stack.length - 1] !== map[char]) {
                return false;
            }
            // It's a match, pop the opening bracket from the stack.
            stack.pop();
        } else {
            // If it's an opening bracket, push it onto the stack.
            stack.push(char);
        }
    }

    // If the stack is empty, all brackets were matched correctly.
    // A non-empty stack means there are unclosed opening brackets.
    return stack.length === 0;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.