File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # 20. Valid Parentheses
3
+
4
+ use stack data structure to perform as a LIFO
5
+
6
+ ## Time and Space Complexity
7
+
8
+ ```
9
+ TC: O(n)
10
+ SC: O(n)
11
+ ```
12
+
13
+ #### TC is O(n):
14
+ - iterating through the string just once to check if the parentheses are valid. = O(n)
15
+
16
+ #### SC is O(n):
17
+ - using a stack to store the parentheses. = the worst case is O(n)
18
+ - using a map to store the parentheses. = O(1)
19
+
20
+ > for space complexity, fixed space is O(1).
21
+ > 👉 parentheses_map is fixed and its size doesn't grow with the input size.
22
+ > 👉 if the map has much larger size? the space complexity is still O(1).
23
+ '''
24
+
25
+ class Solution :
26
+ def isValid (self , s : str ) -> bool :
27
+ stack = [] # SC: O(n)
28
+ parentheses_map = { # SC: O(1)
29
+ "(" : ")" ,
30
+ "{" : "}" ,
31
+ "[" : "]"
32
+ }
33
+
34
+ for char in s : # TC: O(n)
35
+ if char in parentheses_map :
36
+ stack .append (char )
37
+ else :
38
+ if len (stack ) == 0 or parentheses_map [stack .pop ()] != char :
39
+ return False
40
+
41
+ return not stack
You can’t perform that action at this time.
0 commit comments