Valid Parentheses Problem — Explained with Java Optimizations

Avinash Maurya
June 15, 2025
5 min read
24 views
Valid Parentheses Problem — Explained with Java Optimizations

✅ Valid Parentheses Problem — Explained with Java Optimizations

The Valid Parentheses problem is a classic question asked in coding interviews and on platforms like LeetCode. The goal is to determine whether a given string containing only brackets (()[]{}) is well-formed, meaning every opening bracket has a matching closing bracket in the correct order.


📌 Problem Statement

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

A string is valid if:

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.

✅ Examples:

InputOutputExplanation
"()"trueCorrectly paired
"()[]{}"trueAll types correctly paired
"(]"false[ is not closed by ] properly
"([)]"falseIncorrect nesting
"{[]}"trueProperly nested and matched

🧠 Intuition

We need to:

  1. Track opening brackets.
  2. For every closing bracket, check if it matches the last opened bracket.
  3. If anything mismatches or remains unmatched at the end, the string is invalid.

This is a perfect use case for a stack — Last-In-First-Out (LIFO) structure.


💡 Optimal Stack-Based Java Solution

import java.util.Deque; import java.util.ArrayDeque; class Solution { public boolean isValid(String s) { Deque<Character> stack = new ArrayDeque<>(); for (char c : s.toCharArray()) { if (c == '(') stack.push(')'); else if (c == '{') stack.push('}'); else if (c == '[') stack.push(']'); else { if (stack.isEmpty() || stack.pop() != c) return false; } } return stack.isEmpty(); } }

✅ Time & Space Complexity

AspectComplexity
TimeO(n)
SpaceO(n)

We scan the string once and use a stack that can hold up to n characters.


🔥 Ultra-Optimized Java (No Boxing, Fastest)

If you're aiming for 0ms on LeetCode and avoiding Java collection overhead, use a raw array:

class Solution { public boolean isValid(String s) { char[] stack = new char[s.length()]; int top = -1; for (char c : s.toCharArray()) { if (c == '(' || c == '{' || c == '[') { stack[++top] = c; } else { if (top == -1) return false; char open = stack[top--]; if ((c == ')' && open != '(') || (c == '}' && open != '{') || (c == ']' && open != '[')) { return false; } } } return top == -1; } }

🚀 Why this is faster:

  • No Character object boxing/unboxing.
  • No Deque or method call overhead.
  • Tight loop with primitive types.

🤔 Why Some Submissions Show 0ms?

You're not alone if you wonder: Why does someone get 0ms and I get 2ms?

It's due to:

  • Execution environment randomness.
  • JVM warm-up time.
  • Input size/load on LeetCode server.
  • Java timer granularity (below ~1ms rounds to 0ms).

So don’t worry — your algorithm is already optimal.


🧪 Test Cases to Try

System.out.println(isValid("()")); // true System.out.println(isValid("()[]{}")); // true System.out.println(isValid("(]")); // false System.out.println(isValid("([)]")); // false System.out.println(isValid("{[]}")); // true System.out.println(isValid("")); // true (empty is valid) System.out.println(isValid("(((((")); // false

📚 Conclusion

  • Use a stack to track brackets.
  • Optimize with ArrayDeque or char[] based on performance needs.
  • You can’t do better than O(n) — that’s the lower bound for reading all characters.

✅ If you're using the array-based method above, you're already at peak efficiency.


🔁 Related Posts

If you enjoyed this post, you might also find these helpful:


🚀 Explore More & Work With Us

🔧 Try Our Free Tools

We believe in empowering creators and developers. Here are some completely free tools we've built that might help you:

More tools coming soon on GILASA GROUP

💼 Hire Us for Custom Software Development

Whether you're looking to build a custom website, AI tool, or full-fledged SaaS product, our expert team is here to help.

👉 Work With Us – Let’s build something amazing together!

Comments (0)

Leave a Comment