Practice › Stack & Queue
Minimum Additions to Make Parentheses Valid
Easy · Stack & Queue · Asked at Amazon, Meta, Microsoft
The string contains only ( and ). Print the minimum number of parentheses you must insert (anywhere) to make it a valid parentheses string.
Input
A single line with the string.
Output
The minimum number of insertions.
Constraints
- 1 ≤ length ≤ 10^5
Scan with a counter of unmatched
(. A)with nothing to match needs one inserted(. At the end, every unmatched(needs one).
Example 1
Input
())
Output
1
Example 2
Input
(((
Output
3
Hints
- You do not need a real stack — only the number of unmatched
(. - A
)that has no(to match needs one inserted(. - Every
(still open at the end needs one).
Approach
Scan left to right with open = number of unmatched '('. On '(' increase it. On ')': if open > 0, it matches one — decrease open; otherwise this ')' can never be matched by anything to its left, so count one insertion. The answer is the insertions counted plus the '(' still open at the end.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
long long open = 0, add = 0;
for (char c : s) {
if (c == '(') open++;
else if (open > 0) open--;
else add++;
}
cout << add + open << "\n";
return 0;
}Python solution
s = input().strip()
open_count = add = 0
for c in s:
if c == "(":
open_count += 1
elif open_count > 0:
open_count -= 1
else:
add += 1
print(add + open_count)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
long open = 0, add = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') open++;
else if (open > 0) open--;
else add++;
}
System.out.println(add + open);
}
}Solve Minimum Additions to Make Parentheses Valid online · All practice problems