-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy path0921. Minimum Add to Make Parentheses Valid.js
83 lines (80 loc) · 2.1 KB
/
0921. Minimum Add to Make Parentheses Valid.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.
//
// Formally, a parentheses string is valid if and only if:
//
// - It is the empty string, or
// - It can be written as AB (A concatenated with B), where A and B are valid strings, or
// - It can be written as (A), where A is a valid string.
//
// Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.
//
// Example 1:
//
// Input: "())"
// Output: 1
//
// Example 2:
//
// Input: "((("
// Output: 3
//
// Example 3:
//
// Input: "()"
// Output: 0
//
// Example 4:
//
// Input: "()))(("
// Output: 4
//
// Note:
//
// - S.length <= 1000
// - S only consists of '(' and ')' characters.
/**
* @param {string} S
* @return {number}
*/
// 1) Balance
// O(n)
// O(1)
//
// Keep track of the balance of the string: the number of '(''s minus the number of ')''s. A string is valid if
// its balance is 0, plus every prefix has non-negative balance.
//
// The above idea is common with matching brackets problems, but could be difficult to find if you haven't seen it before.
//
// Now, consider the balance of every prefix of S. If it is ever negative (say, -1), we must add a '(' bracket.
// Also, if the balance of S is positive (say, +B), we must add B ')' brackets at the end.
const minAddToMakeValid1 = (S) => {
let count = 0;
let bal = 0;
for (let c of S) {
bal += c === '(' ? 1 : -1;
if (bal === -1) {
count++;
bal++;
}
}
return count + bal;
};
// 2) Easier to understand than 1)
// O(n)
// O(1)
//
// The key to solve this problem is in recognizing that right ) parentheses that are at the left side cannot be
// closed by left ( parentheses. That why in my solution I have two counters and the right one only goes up.
const minAddToMakeValid = (S) => {
let l = 0;
let r = 0;
for (const c of S) {
if (c === ')') {
if (l === 0) r++; // ) are at the left side cannot be closed by (
else l--;
} else {
l++;
}
}
return l + r;
};