Return to site

🚀 Crack coding interview: Valid Parentheses (Stack)

· java

📐 Problem

Given a string containing only ()[]{}, determine if it’s well-formed: every opening bracket has a matching closing bracket in the correct order.

Java Solution (Stack + Map)

import java.util.*;
public class ValidParentheses {
 public boolean isValid(String s) {
 if ((s.length() & 1) == 1) return false; // odd length can't be balanced

 Map<Character, Character> match = Map.of(
 ')','(', ']','[', '}','{'
 );
 Deque<Character> st = new ArrayDeque<>();

 for (char c : s.toCharArray()) {
 if (c == '(' || c == '[' || c == '{') {
 st.push(c);
 } else {
 if (st.isEmpty() || st.pop() != match.get(c)) return false;
 }
 }
 return st.isEmpty();
 }

 // quick demo
 public static void main(String[] args) {
 ValidParentheses vp = new ValidParentheses();
 System.out.println(vp.isValid("()[]{}")); // true
 System.out.println(vp.isValid("([{}])")); // true
 System.out.println(vp.isValid("(]")); // false
 System.out.println(vp.isValid("([)]")); // false
 System.out.println(vp.isValid("(((())))")); // true
 }
}

🧠 Complexity

Time: O(n) — each char is pushed/popped at most once.

Space: O(n) — worst case all openings on the stack.

☝️ Takeaway

This question is a perfect showcase for stack thinking: push on open, pop on close, and match pairs. It’s also great for discussing edge cases (odd length, early closing, leftovers) and why a stack beats a simple counter.

#java #codinginterview #interviewprep #algorithms #datastructures #stack #leetcode #programming #javaprogramming #bigO

Go further with Java certification:

Java👇

Spring👇

SpringBook👇