The Valid Parentheses problem requires determining whether a string containing brackets has valid and properly matched parentheses.

Problem

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

A string is valid if every opening bracket is closed by the same type of bracket in the correct order.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

s = "()[]{}"

Output

true

Solution

This solution uses a Stack to keep track of opening brackets. When an opening bracket is encountered, it is pushed onto the stack.

When a closing bracket is encountered, the top element of the stack must contain its corresponding opening bracket. If the stack is empty or the brackets do not match, the string is invalid.

After processing all characters, the string is valid only if the stack is empty.
public boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();

    for (char c : s.toCharArray()) {
        if (c == '(' || c == '{' || c == '[') {
            stack.push(c);
        } else {
            if (stack.isEmpty()) {
                return false;
            }

            char top = stack.pop();

            if ((c == ')' && top != '(') ||
                (c == '}' && top != '{') ||
                (c == ']' && top != '[')) {
                return false;
            }
        }
    }

    return stack.isEmpty();
}

Complexity

The algorithm processes each character exactly once, resulting in a time complexity of O(n).

In the worst case, all characters may be opening brackets and stored in the stack, resulting in an extra space complexity of O(n).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion