Skip to content

Commit c0204ce

Browse files
committed
add solution: valid-parentheses
1 parent 42c3949 commit c0204ce

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

valid-parentheses/dusunax.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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

0 commit comments

Comments
 (0)