The “Valid Parentheses” problem asks us to determine whether a string of brackets is properly balanced. A string is valid if:
For example:
"()[]{}"
→ true
"(]"
→ false
"([{}])"
→ true
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.
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.
{')': '(', ']': '[', '}': '{'}
'('
, '{'
, '['
), push it onto the stack.false
— there's nothing to match.false
.true
only if the stack is empty (all brackets were matched).
Input: "({[]})"
Execution:
Stack is empty → return true
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.
true
false
false
false
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.