← Back to All Algorithms

Easy Interview Frequency: ⭐⭐⭐⭐⭐

Valid Parentheses

Determine whether a string of brackets is valid. Each opening bracket must be closed by the same type and in the correct order.

Stack

📚 Table of Contents

  1. Problem Statement
  2. Real-World Analogy
  3. Key Insights
  4. Solution Approaches
  5. Step-by-Step Walkthrough
  6. Complexity Analysis
  7. Edge Cases
  8. Test Cases
  9. Interview Tips
  10. Key Takeaways

📋 Problem Statement

You are given a string s containing only characters ()[]{}. Return true if the string is valid.

Examples

Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false

🎯 Real-World Analogy

Plate Stack at a Restaurant

In a stack of plates, the last plate you place is the first one you remove. Bracket matching works exactly the same way: the most recently opened bracket must close first.

If a close bracket arrives that does not match the top of the stack, the order is broken.

💡 Key Insights

💻 Solution Approaches

Approach 1: Repeated String Replacement (Not Ideal)

Time: O(N²) worst-case | Space: O(N)

Repeatedly replace (), [], and {} until no changes. Works for simple cases but performs poorly.

Approach 2: Stack with Pair Map (Recommended)

Time: O(N) | Space: O(N)

Keep opening brackets on stack. On each closing bracket, pop and compare expected pair.

Python Implementation

def is_valid(s: str) -> bool: """ Validate parentheses/brackets/braces in proper nesting order. Time: O(N) Space: O(N) """ pairs = {")": "(", "]": "[", "}": "{"} stack = [] for ch in s: if ch in "([{": stack.append(ch) else: if not stack: return False top = stack.pop() if top != pairs[ch]: return False return len(stack) == 0

JavaScript Implementation

function isValid(s) { /** * Time: O(N) * Space: O(N) */ const pairs = { ')': '(', ']': '[', '}': '{', }; const stack = []; for (const ch of s) { if (ch === '(' || ch === '[' || ch === '{') { stack.push(ch); } else { if (stack.length === 0) return false; const top = stack.pop(); if (top !== pairs[ch]) return false; } } return stack.length === 0; }

🔍 Step-by-Step Walkthrough

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

Read ( -> push -> stack: [(]
Read [ -> push -> stack: [(, []
Read { -> push -> stack: [(, [, {]
Read } -> pop {, matches ✓
Read ] -> pop [, matches ✓
Read ) -> pop (, matches ✓
Stack empty at end -> valid

⚡ Complexity Analysis

Time Complexity: O(N)

Space Complexity: O(N)

🔧 Edge Cases

🧪 Test Cases

Case 1
"()[]{}" -> true
Case 2
"(]" -> false
Case 3
"([{}])" -> true

💼 Interview Tips

🎓 Key Takeaways

← Back to All Algorithms