Minimum number of Parentheses to be added to make it valid
Last Updated :
09 May, 2023
Given a string S of parentheses '(' or ')' where, 0\leq len(S)\leq 1000 . The task is to find a minimum number of parentheses '(' or ')' (at any positions) we must add to make the resulting parentheses string is valid.
Examples:
Input: str = "())"
Output: 1
One '(' is required at beginning.
Input: str = "((("
Output: 3
Three ')' is required at end.
Approach 1: Iterative Approach
We keep the track of balance of the string i:e the number of '(' minus the number of ')'. A string is valid if its balance is 0, and also every prefix has non-negative balance.
Now, consider the balance of every prefix of S. If it is ever negative (say, -1), we must add a '(' bracket at the beginning. Also, if the balance of S is positive (say, +P), we must add P times ')' brackets at the end.
Below is the implementation of the above approach:
C++
// C++ Program to find minimum number of '(' or ')'
// must be added to make Parentheses string valid.
#include <bits/stdc++.h>
using namespace std;
// Function to return required minimum number
int minParentheses(string p)
{
// maintain balance of string
int bal = 0;
int ans = 0;
for (int i = 0; i < p.length(); ++i) {
bal += p[i] == '(' ? 1 : -1;
// It is guaranteed bal >= -1
if (bal == -1) {
ans += 1;
bal += 1;
}
}
return bal + ans;
}
// Driver code
int main()
{
string p = "())";
// Function to print required answer
cout << minParentheses(p);
return 0;
}
Java
// Java Program to find minimum number of '(' or ')'
// must be added to make Parentheses string valid.
public class GFG {
// Function to return required minimum number
static int minParentheses(String p)
{
// maintain balance of string
int bal = 0;
int ans = 0;
for (int i = 0; i < p.length(); ++i) {
bal += p.charAt(i) == '(' ? 1 : -1;
// It is guaranteed bal >= -1
if (bal == -1) {
ans += 1;
bal += 1;
}
}
return bal + ans;
}
public static void main(String args[])
{
String p = "())";
// Function to print required answer
System.out.println(minParentheses(p));
}
// This code is contributed by ANKITRAI1
}
Python3
# Python3 Program to find
# minimum number of '(' or ')'
# must be added to make Parentheses
# string valid.
# Function to return required
# minimum number
def minParentheses(p):
# maintain balance of string
bal=0
ans=0
for i in range(0,len(p)):
if(p[i]=='('):
bal+=1
else:
bal+=-1
# It is guaranteed bal >= -1
if(bal==-1):
ans+=1
bal+=1
return bal+ans
# Driver code
if __name__=='__main__':
p = "())"
# Function to print required answer
print(minParentheses(p))
# this code is contributed by
# sahilshelangia
C#
// C# Program to find minimum number
// of '(' or ')' must be added to
// make Parentheses string valid.
using System;
class GFG
{
// Function to return required
// minimum number
static int minParentheses(string p)
{
// maintain balance of string
int bal = 0;
int ans = 0;
for (int i = 0; i < p.Length; ++i)
{
bal += p[i] == '(' ? 1 : -1;
// It is guaranteed bal >= -1
if (bal == -1)
{
ans += 1;
bal += 1;
}
}
return bal + ans;
}
// Driver code
public static void Main()
{
string p = "())";
// Function to print required answer
Console.WriteLine(minParentheses(p));
}
}
// This code is contributed
// by Kirti_Mangal
PHP
<?php
// PHP Program to find minimum number of
// '(' or ')' must be added to make
// Parentheses string valid.
// Function to return required minimum number
function minParentheses($p)
{
// maintain balance of string
$bal = 0;
$ans = 0;
for ($i = 0; $i < strlen($p); ++$i)
{
if ($p[$i] == '(' )
$bal += 1 ;
else
$bal += -1;
// It is guaranteed bal >= -1
if ($bal == -1)
{
$ans += 1;
$bal += 1;
}
}
return $bal + $ans;
}
// Driver code
$p = "())";
// Function to print required answer
echo minParentheses($p);
// This code is contributed by ita_c
?>
JavaScript
<script>
// Javascript Program to find minimum number of '(' or ')'
// must be added to make Parentheses string valid.
// Function to return required minimum number
function minParentheses( p)
{
// maintain balance of string
var bal = 0;
var ans = 0;
for (var i = 0; i < p.length; ++i) {
bal += p[i] == '(' ? 1 : -1;
// It is guaranteed bal >= -1
if (bal == -1) {
ans += 1;
bal += 1;
}
}
return bal + ans;
}
var p = "())";
// Function to print required answer
document.write( minParentheses(p));
// This code is contributed by SoumikMondal
</script>
Complexity Analysis:
- Time Complexity: O(N), where N is the length of S.
- Space Complexity: O(1).
Approach 2: Using Stack
We can also solve this problem using a stack data structure.
- We push the index of every '(' character onto the stack, and whenever we encounter a ')' character, we pop the top index from the stack.
- This indicates that the corresponding '(' has been paired with the current ')'.
- If at any point the stack is empty and we encounter a ')' character, it means we need to add a '(' character to the beginning of the string to make it valid.
- Similarly, if after processing the entire string there are still indices left in the stack, it means we need to add ')' characters to the end of the string to make it valid.
Below is the implementation of the above approach:
C++
// C++ Program to find minimum number of '(' or ')'
// must be added to make Parentheses string valid.
#include <bits/stdc++.h>
using namespace std;
// Function to return required minimum number
int minParentheses(string p)
{
stack<int> stk;
int ans = 0;
for (int i = 0; i < p.length(); ++i) {
if (p[i] == '(') {
stk.push(i);
}
else {
if (!stk.empty()) {
stk.pop();
}
else {
ans += 1;
}
}
}
// add remaining '(' characters to end
ans += stk.size();
return ans;
}
// Driver code
int main()
{
string p = "())";
// Function to print required answer
cout << minParentheses(p);
return 0;
}
// This code is contributed by user_dtewbxkn77n
Java
import java.util.Stack;
public class Main {
// Function to return required minimum number
public static int minParentheses(String p) {
Stack<Integer> stk = new Stack<>();
int ans = 0;
for (int i = 0; i < p.length(); ++i) {
if (p.charAt(i) == '(') {
stk.push(i);
} else {
if (!stk.empty()) {
stk.pop();
} else {
ans += 1;
}
}
}
// add remaining '(' characters to end
ans += stk.size();
return ans;
}
// Driver code
public static void main(String[] args) {
String p = "())";
// Function to print required answer
System.out.println(minParentheses(p));
}
}
Python3
def minParentheses(p):
stk = []
ans = 0
for i in range(len(p)):
if p[i] == '(':
stk.append(i)
else:
if len(stk) > 0:
stk.pop()
else:
ans += 1
# add remaining '(' characters to end
ans += len(stk)
return ans
# Driver code
p = "())"
# Function to print required answer
print(minParentheses(p))
C#
using System;
using System.Collections.Generic;
public class Program {
// Function to return required minimum number
public static int MinParentheses(string p) {
Stack<int> stk = new Stack<int>();
int ans = 0;
for (int i = 0; i < p.Length; ++i) {
if (p[i] == '(') {
stk.Push(i);
} else {
if (stk.Count > 0) {
stk.Pop();
} else {
ans += 1;
}
}
}
// add remaining '(' characters to end
ans += stk.Count;
return ans;
}
// Driver code
public static void Main() {
string p = "())";
// Function to print required answer
Console.WriteLine(MinParentheses(p));
}
}
JavaScript
// Function to return required minimum number
function minParentheses(p) {
let stk = [];
let ans = 0;
for (let i = 0; i < p.length; i++) {
if (p[i] === '(') {
stk.push(i);
} else {
if (stk.length > 0) {
stk.pop();
} else {
ans += 1;
}
}
}
// add remaining '(' characters to end
ans += stk.length;
return ans;
}
// Driver code
let p = "())";
// Function to print required answer
console.log(minParentheses(p));
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(n)
Approach 3: Using string manipulation
- Continuously search for the substring "()" in the input string.
- If the substring "()" is found, replace it with an empty string.
- Repeat steps 1 and 2 until the substring "()" can no longer be found.
- The length of the resulting string is the minimum number of parentheses needed to make the string valid.
Here is the implementation of above approach:
C++
#include <iostream>
#include <string>
using namespace std;
int minParentheses(string s) {
while (s.find("()") != -1) {
s.replace(s.find("()"), 2, "");
}
return s.length();
}
int main() {
string s = "(((";
cout << minParentheses(s) << endl;
return 0;
}
Java
public class Solution {
public static int minParentheses(String s) {
while (s.indexOf("()") != -1) {
s = s.replace("()", "");
}
return s.length();
}
public static void main(String[] args) {
String s = "(((";
System.out.println(minParentheses(s));
}
}
Python3
def minParentheses(s: str) -> int:
while s.find("()") != -1:
s = s.replace("()", "")
return len(s)
# Driver code
s = "((("
print(minParentheses(s))
C#
using System;
public class Program {
public static void Main() {
string s = "(((";
Console.WriteLine(minParentheses(s));
}
public static int minParentheses(string s) {
while (s.IndexOf("()") != -1) {
s = s.Replace("()", "");
}
return s.Length;
}
}
JavaScript
function minParentheses(s) {
while(s.indexOf("()") != -1) {
s = s.replace("()", "");
}
return s.length;
}
// Driver code
let s = "(((";
console.log(minParentheses(s));
Time Complexity: O(n^2) where n is the length of the input string. This is because the find() and replace() operations are called repeatedly in a loop.
Auxiliary Space: O(n) where n is the length of the input string. This is because the string s is being replaced in place and no additional data structures are being used.
Similar Reads
Mastering Bracket Problems for Competitive Programming Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve chec
4 min read
Check for balanced with only one type of brackets Given a string str of length N, consisting of '(' and ')' only, the task is to check whether it is balanced or not.Examples:Input: str = "((()))()()" Output: BalancedInput: str = "())((())" Output: Not Balanced Approach 1: Declare a Flag variable which denotes expression is balanced or not.Initialis
9 min read
Valid Parentheses in an Expression Given a string s representing an expression containing various types of brackets: {}, (), and [], the task is to determine whether the brackets in the expression are balanced or not. A balanced expression is one where every opening bracket has a corresponding closing bracket in the correct order.Exa
8 min read
Length of longest balanced parentheses prefix Given a string of open bracket '(' and closed bracket ')'. The task is to find the length of longest balanced prefix. Examples: Input : S = "((()())())((" Output : 10From index 0 to index 9, they are forming a balanced parentheses prefix.Input : S = "()(())((()"Output : 6The idea is take value of op
9 min read
Modify a numeric string to a balanced parentheses by replacements Given a numeric string S made up of characters '1', '2' and '3' only, the task is to replace characters with either an open bracket ( '(' ) or a closed bracket ( ')' ) such that the newly formed string becomes a balanced bracket sequence. Note: All occurrences of a character must be replaced by the
10 min read
Check if the bracket sequence can be balanced with at most one change in the position of a bracket Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(
6 min read
Number of closing brackets needed to complete a regular bracket sequence Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete th
7 min read
Minimum number of Parentheses to be added to make it valid Given a string S of parentheses '(' or ')' where, 0\leq len(S)\leq 1000 . The task is to find a minimum number of parentheses '(' or ')' (at any positions) we must add to make the resulting parentheses string is valid. Examples: Input: str = "())" Output: 1 One '(' is required at beginning. Input: s
9 min read
Minimum bracket reversals to make an expression balanced Given an expression with only '}' and '{'. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.Examples: Input: s = "}{{}}{{{"Output: 3Explanation: We need to reverse minimum 3 brackets to make "{{{}}{}}". Input: s = "{{"Output: 1Explanation:
15+ min read
Find the number of valid parentheses expressions of given length Given a number n, the task is to find the number of valid parentheses expressions of that length. Examples : Input: 2Output: 1 Explanation: There is only possible valid expression of length 2, "()"Input: 4Output: 2 Explanation: Possible valid expression of length 4 are "(())" and "()()" Input: 6Outp
11 min read