20. Valid Parentheses
Solving the "Valid Parentheses" Problem with Stack
The Valid Parentheses problem is a common question that comes up in coding interviews. The task is to determine whether a given string containing only parentheses—round (), square [], and curly {} brackets—is valid. A string is valid if:
- Every opening bracket has a corresponding closing bracket of the same type.
- Brackets are closed in the correct order (i.e., an opening bracket must be closed before another of a different type is opened).
Example
Input:
"{[()]}"
Output:true
This is valid since each opening bracket is closed properly in the right order.Input:
"{[(])}"
Output:false
This is invalid because the brackets are mismatched.
Approach: Using a Stack
A stack is a perfect data structure for solving this problem because it follows a Last In, First Out (LIFO) principle. When we encounter an opening bracket, we push it onto the stack. When we encounter a closing bracket, we check if it matches the most recent (top) opening bracket. If it does, we pop the top element off the stack. Otherwise, the string is invalid.
At the end of this process, if the stack is empty, it means all the opening brackets were matched properly, and the string is valid. If the stack still contains elements, it means there are unmatched opening brackets, and the string is invalid.
Time and Space Complexity
- Time Complexity: O(n), where
nis the length of the string. We traverse the string once, and all stack operations (push and pop) take constant time. - Space Complexity: O(n), where
nis the length of the string. In the worst case, all characters in the string are opening brackets, so the stack will holdncharacters.
Comments
Post a Comment