This article is another part of a series on leet code problems solutions, and it provides a solution to the leet code problem number 20. This is a Leet code problem named Valid Parentheses. We will solve it using python and it is the best space and time-optimized solution.
Question of 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.
Example
Example 1
Input: s = "()"
Output: true
Example 2
Input: s = "()[]{}"
Output: true
Example 3
Input: s = "(]"
Output: false
Constraints
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
Approach to solve Valid Parentheses
To solve this we traverse through each character of string which consists of sign {}()[] only. When an open parenthesis comes like {, [, ( we push it into the stack. And when the closing parenthesis comes like }, ], ) we compare it from the top of the stack. If the closing parenthesis matches with the top of stack then we pop the stack otherwise we return the false.
Algorithm
This method performs the following steps for a given input array:
- Create a stack to store Parentheses.
- Repeat steps from 3 to 10 till there is a parenthesis in the string.
- Check if it opening Parentheses then push it into stack.
- If it is closing Parentheses then check the length of the stack is greater than 0 or not.
- If Yes then do steps 6 and 7 otherwise do step 9.
- pop the last element.
- if the element is not the opposite of popped element then return false.
- end if
- return false
- end if
- end for
- return true
Python Code for Valid Parentheses
class Solution:
def isValid(self, s: str) -> bool:
#stack to store Parentheses
stack = []
#run through each Parentheses
for i in s:
#Check if it opening Parentheses then push it into stack
if i=='(' or i =='[' or i=='{':
stack.append(i)
#If it closing Parentheses then check length of stack is greater than 0 or not
elif(len(stack)):
#pop the last element
el = stack.pop()
#if element is not opposite of popped element than return false
if el=='(' and i !=')':
return False
elif el=='[' and i !=']':
return False
elif el=='{' and i !='}':
return False
#If above 2 condition fails return false
else:
return False
#if there is any Parentheses in stack return false
if(len(stack)):
return False
#otherwise return true
else:
return True
Complexity Analysis
Time Complexity: O(n)
As we iterate through the whole string
Space Complexity: O(n)
Space used by Stack.
So here is the end of the post. If you find any issues or any questions then write a comment. Share with your friends.
Related Posts:
- Find Pivot Index (Leet Code-724)
- Spiral Matrix Problem Solution
- Isomorphic Strings
- Two Sum IV - Input is a BST (Leet Code-653)
- Search in a Binary Search Tree (Leet Code-700)
- Invert Binary Tree (Leet Code-266)
- Symmetric Tree (Leet Code-101)
- Maximum Depth of Binary Tree (Leet Code-104)
- Binary Tree Postorder Traversal (Leet Code-145)
- Binary Tree Inorder Traversal (Leet Code - 94)
- Binary Tree Pre-Order Traversal
- Binary Tree Level Order Traversal (Leet Code-102)
- Remove Duplicates from Sorted List (Leet Code-83)
- Reverse Linked List (Leet code -206)
- Remove Linked List Elements (Leet Code-203)
- Merge Two Sorted Lists (Leet code-21)
- Ransom Note (Leet code-383)
- First Unique Character in a String (Leet code-387)
- Valid Sudoku (Leet Code-36)
- Search a 2D Matrix (Leet Code-74)
- Linked List Cycle (Leet Code-141)
- Pascal's Triangle (Leet Code - 118)
- Reshape the Matrix (Leet Code-566)
- Best Time to Buy and Sell Stock (Leet code-121)
- The Intersection of Two Arrays II (Leet Code)
- Binary Search - Leet Code
- Two Sum - Leet Code
it was helpful. thank you.