20. Valid Parentheses
🟩 Easy
Question
Given a string 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.
Note that an empty string is also considered valid.
Examples:
Stack
Initialize a stack S.
Process each bracket of the expression one at a time.
If we encounter an opening bracket, we simply push according closing bracket onto the stack.
If we encounter a closing bracket, then we check the element on top of the stack. If the element at the top of the stack is same, then we pop it off the stack and continue processing. Else, this implies an invalid expression.
In the end, if we are left with a stack still having elements, then this implies an invalid expression.
Complexity
Time complexity: O(n)
Space complexity: O(1)
Code
Last updated
Was this helpful?