Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›Stacks & Queues›Valid Parentheses
EasyStacks & Queues

Valid Parentheses

stackstring

Problem

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

An input string is valid if open brackets are closed by the same type in the correct order.

Examples

Example 1

Input: s = "()"

Output: true

Example 2

Input: s = "()[]{}"

Output: true

Example 3

Input: s = "(]"

Output: false

Constraints

  • •1 <= s.length <= 10^4

Hints

Hint 1

Use a stack. Push open brackets; match close brackets against the top.

Solutions

public boolean isValid(String s) {
    Deque<Character> stack = new ArrayDeque<>();
    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 != '(') return false;
            if (c == ']' && top != '[') return false;
            if (c == '}' && top != '{') return false;
        }
    }
    return stack.isEmpty();
}
Java

Time: O(n) · Space: O(n)