-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1. validParanthesis.py
More file actions
46 lines (36 loc) · 1.14 KB
/
1. validParanthesis.py
File metadata and controls
46 lines (36 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
Problem: Valid Parentheses
LeetCode: https://leetcode.com/problems/valid-parentheses/
Time Complexity: O(n)
Space Complexity: O(n)
Why optimal: Stack is the standard data structure for matching nested structures like parentheses.
"""
#Check balanced paranthesis in a string
#Idea
# Use a stack to keep track of opening paranthesis
# For every closing paranthesis, check if it matches the top of the stack
# If stack is empty at the end, paranthesis are balanced
def is_valid_parentheses(s):
stack = []
# Mapping closing → opening
match = {')': '(', '}': '{', ']': '['}
for ch in s:
# Opening bracket
if ch in match.values():
stack.append(ch)
else:
# Closing bracket with no opening
if not stack:
return False
top = stack.pop()
if match[ch] != top:
return False
# Valid only if stack is empty
return len(stack) == 0
# Example usage
s = "{[()]}"
print(is_valid_parentheses(s)) # Output: True
s = "{[(])}"
print(is_valid_parentheses(s)) # Output: False
# Time Complexity: O(n)
# Space Complexity: O(n)