Parens Oracle: Valid Parentheses
๐ฆ Parens Oracle: Valid Parentheses
Difficulty: Beginner Tags: stack, strings, validation, matching Series: CS 102: Problem Solving & Logic
Problem
In the mystical realm of code, the Oracle guards the balance of parentheses. Your task is to validate whether a string of brackets is properly balanced.
Given a string containing only the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
A string is valid if: 1. Every opening bracket has a corresponding closing bracket of the same type 2. Opening brackets are closed in the correct order 3. Every closing bracket has a corresponding opening bracket of the same type
Real-World Application
Bracket validation appears in: - Code editors - syntax validation, auto-completion - Compilers - parsing expressions and code blocks - Markup languages - HTML/XML tag matching - Mathematical expressions - validating formulas - Configuration files - JSON/YAML validation - Regular expressions - pattern validation - Text editors - bracket highlighting and matching
Input
data = str # String containing only brackets: ()[]{}
Output
bool # True if valid, False otherwise
Constraints
- String length โค 100,000
- String contains only bracket characters
- Empty string is considered valid
Examples
Example 1: Simple Valid
Input: "()[]{}"
Output: True
Explanation:
- () - valid pair
- [] - valid pair
- {} - valid pair
- All balanced and in order
Example 2: Mismatched Type
Input: "(]"
Output: False
Explanation:
- ( opens, but ] is wrong closing type
- Not valid
Example 3: Nested Valid
Input: "([{}])"
Output: True
Explanation:
- ( opens
- [ opens (nested)
- { opens (nested deeper)
- } closes { โ
- ] closes [ โ
- ) closes ( โ
- Proper nesting order
Example 4: Wrong Order
Input: "([)]"
Output: False
Explanation:
- ( opens, [ opens
- ) tries to close (, but [ is still open
- Wrong closing order
Example 5: Unclosed
Input: "("
Output: False
Explanation: - Opening bracket with no closing - Not valid
Example 6: Empty String
Input: ""
Output: True
Explanation: - Empty string is considered valid - No unbalanced brackets
Example 7: Only Closing
Input: ")"
Output: False
Explanation: - Closing bracket with no opening - Not valid
What You'll Learn
- Stack-based problem solving
- Matching pairs with LIFO (Last-In-First-Out) order
- Using hash maps for lookup
- Early exit optimization
Why This Matters
This is a top 10 coding interview question that tests: - Understanding of stack data structure - Pattern matching and validation - The LIFO principle - Ability to recognize when to use stacks
Starter Code
def challenge_function(data):
"""
Validate if brackets are properly balanced and ordered.
Args:
data: string containing only brackets: ()[]{}
Returns:
bool: True if valid, False otherwise
"""
# Your implementation here
pass