Valid Parentheses - Leetcode Solution


đź’ˇ Step-by-Step Thought Process

  1. Understand the problem: Determine if a string of parentheses is valid, where each opening parenthesis has a matching closing parenthesis in the correct order.
  2. Create a hash map mapping closing parentheses (")", "}", "]") to their corresponding opening parentheses ("(", "{", "[").
  3. Initialize an empty stack to store opening parentheses.
  4. Iterate through each character c in the input string s.
  5. If c is not a closing parenthesis (i.e., not in the hash map), push c onto the stack.
  6. If c is a closing parenthesis, check if the stack is empty; if so, return False.
  7. Pop the top character from the stack and check if it matches the corresponding opening parenthesis for c using the hash map.
  8. If they don’t match, return False.
  9. After the loop, return True if the stack is empty (all parentheses matched); otherwise, return False.

Code Solution


                

                

                

                

Detailed Explanation

Understanding the Problem: Valid Parentheses

The “Valid Parentheses” problem asks us to determine whether a string of brackets is properly balanced. A string is valid if:

  • Open brackets are closed by the same type of brackets.
  • Brackets are closed in the correct order.
  • Every closing bracket has a corresponding open bracket of the same type.

For example:

  • "()[]{}" → true
  • "(]" → false
  • "([{}])" → true

Why This Problem Matters

This is a fundamental problem in understanding how stacks work. It also has real-world applications in parsing expressions, validating compilers, and building interpreters. It's often one of the first problems used to introduce stack-based algorithms in interviews and technical assessments.

Approach: Stack-Based Matching

A stack is ideal for this problem because of its LIFO (Last In, First Out) behavior, which matches the requirement that the most recently opened parenthesis must be the first to close.

Steps:

  1. Create a dictionary that maps closing brackets to their matching opening brackets: {')': '(', ']': '[', '}': '{'}
  2. Initialize an empty stack.
  3. Loop through each character in the string:
    • If the character is an opening bracket ('(', '{', '['), push it onto the stack.
    • If it's a closing bracket, check if the stack is empty. If it is, return false — there's nothing to match.
    • Otherwise, pop the top of the stack and ensure it matches the corresponding opening bracket from the dictionary.
    • If it doesn’t match, return false.
  4. After processing all characters, return true only if the stack is empty (all brackets were matched).

Example Walkthrough

Input: "({[]})"
Execution:

  • '(' → push → stack: ['(']
  • '{' → push → stack: ['(', '{']
  • '[' → push → stack: ['(', '{', '[']
  • ']' → pop '[' → match → stack: ['(', '{']
  • '}' → pop '{' → match → stack: ['(']
  • ')' → pop '(' → match → stack: []

Stack is empty → return true

Time and Space Complexity

Time Complexity: O(n), where n is the length of the string. Each character is processed once.
Space Complexity: O(n) in the worst case, if all characters are opening brackets and must be stored in the stack.

Edge Cases to Consider

  • Empty string → valid, return true
  • Unmatched closing bracket → return false
  • Nested but misordered brackets → return false
  • One unmatched opening bracket remaining at the end → return false

Conclusion

The “Valid Parentheses” problem is an elegant introduction to stacks and matching logic. By using a dictionary for bracket relationships and a stack for ordering, we can efficiently determine whether the parentheses are balanced and properly nested. Mastering this technique lays the groundwork for more complex parsing problems in code analysis, math expression evaluation, and beyond.

Get Personalized Support at AlgoMap Bootcamp đź’ˇ