File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution :
2+ def minAddToMakeValid (self , s : str ) -> int :
3+ """
4+ LeetCode 921 - Minimum Add to Make Parentheses Valid
5+
6+ Approach:
7+ - Use a stack to keep track of unmatched opening parentheses '('.
8+ - Traverse each character in the string:
9+ 1. If the character is '(', push it onto the stack.
10+ 2. If the character is ')':
11+ - If the stack is not empty, pop one '(' as it forms a valid pair.
12+ - Otherwise, increment 'count' because an extra '(' is needed.
13+ - After the traversal, any remaining '(' in the stack require matching ')'.
14+
15+ Return:
16+ - count + len(stack)
17+ where:
18+ count -> number of unmatched ')'
19+ len(stack) -> number of unmatched '('
20+
21+ Example:
22+ Input: s = "()))(("
23+
24+ Traversal:
25+ '(' -> push
26+ ')' -> pop
27+ ')' -> stack empty -> count = 1
28+ ')' -> stack empty -> count = 2
29+ '(' -> push
30+ '(' -> push
31+
32+ Result:
33+ count = 2
34+ len(stack) = 2
35+ Answer = 2 + 2 = 4
36+
37+ Time Complexity: O(n)
38+ - Each character is processed once.
39+
40+ Space Complexity: O(n)
41+ - In the worst case, the stack stores all opening parentheses.
42+ """
43+
44+ count = 0
45+ stack = []
46+
47+ for i in range (len (s )):
48+ if s [i ] == "(" :
49+ stack .append (s [i ])
50+ else :
51+ if stack :
52+ stack .pop ()
53+ else :
54+ count += 1
55+
56+ return count + len (stack )
You can’t perform that action at this time.
0 commit comments