Problem Number: 20 Difficulty: Easy Category: String, Stack LeetCode Link: https://leetcode.com/problems/valid-parentheses/
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
1 <= s.length <= 10^4sconsists of parentheses only'()[]{}'
I used a Stack approach to validate the parentheses. The key insight is to use a stack to keep track of opening brackets and match them with closing brackets in the correct order.
Algorithm:
- Create a hash map mapping closing brackets to their corresponding opening brackets
- Initialize an empty stack
- Iterate through each character in the string
- If it's an opening bracket, push it onto the stack
- If it's a closing bracket, check if the top of stack matches the corresponding opening bracket
- If match found, pop from stack; otherwise return false
- Return true if stack is empty at the end
The solution uses a stack to validate parentheses matching. See the implementation in the solution file.
Key Points:
- Uses a hash map to map closing brackets to opening brackets
- Stack stores opening brackets in order of appearance
- Validates matching brackets and correct order
- Handles edge cases like empty string and single characters
Time Complexity: O(n)
- We traverse the string once
- Stack operations (push/pop) are O(1)
- Hash map lookups are O(1)
- Total: O(n)
Space Complexity: O(n)
- Stack can store up to n/2 opening brackets in worst case
- Hash map has constant size (3 pairs)
- Total: O(n)
-
Stack for Order Tracking: Stack naturally handles the "last in, first out" order required for parentheses matching.
-
Hash Map for Mapping: Using a hash map to map closing brackets to opening brackets makes the code cleaner and more efficient.
-
Early Termination: We can return false immediately when we encounter a mismatch or when trying to pop from an empty stack.
-
Stack Empty Check: At the end, the stack must be empty for the string to be valid (all brackets must be matched).
-
Single Character Handling: Strings with odd length or single characters are automatically invalid.
-
Order Validation: The stack ensures that brackets are closed in the correct order (most recent opening bracket must be closed first).
-
Wrong Data Structure: Initially might use a simple counter approach, which doesn't handle order correctly.
-
Missing Edge Cases: Not properly handling empty strings or strings with single characters.
-
Incorrect Mapping: Using wrong mapping between opening and closing brackets.
-
Stack Empty Check: Forgetting to check if the stack is empty at the end.
- Generate Parentheses (Problem 22): Generate all valid parentheses combinations
- Longest Valid Parentheses (Problem 32): Find longest valid parentheses substring
- Remove Invalid Parentheses (Problem 301): Remove minimum parentheses to make string valid
- Check If a Parentheses String Can Be Valid (Problem 2116): More complex validation
- Counter Approach: Use counters for each bracket type (doesn't handle order correctly)
- Recursive: Use recursion to validate nested parentheses
- Two Pass: First pass to count brackets, second pass to validate order
- Wrong Order Handling: Not using a stack and thus not handling the order correctly.
- Missing Edge Cases: Not handling empty strings or single characters.
- Incorrect Mapping: Using wrong bracket pairs in the mapping.
- Stack Empty Check: Not checking if the stack is empty at the end.
- Early Termination: Not returning false immediately when encountering mismatches.
Note: This is a fundamental stack problem that introduces the concept of using a stack to validate matching pairs in the correct order.