
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Minimum number of Parentheses to be added to make it valid in C++
Problem statement
Given a string of parentheses. It can container opening parentheses ’(‘ or closing parentheses ‘)’. We have to find minimum number of parentheses to make the resulting parentheses string is valid.
Example
If str = “((()” then we required 2 closing parentheses i.e ‘))’ at end of string
Algorithm
- Count opening parentheses
- Count closing parentheses
- Required parentheses = abs(no. of opening parentheses – no. of closing parentheses)
Example
#include <iostream> #include <string> #include <cmath> using namespace std; int requiredParentheses(string str) { int openingParentheses = 0, closingParentheses = 0; for (int i = 0; i < str.length(); ++i) { if (str[i] == '(') { ++openingParentheses; } else if (str[i] == ')') { ++closingParentheses; } } return abs(openingParentheses - closingParentheses); } int main() { string str = "((()"; cout << "Required parentheses = " << requiredParentheses(str) << endl; return 0; }
When you compile and execute above program. It generates following output −
Required parentheses = 2
- Related Articles
- Minimum Remove to Make Valid Parentheses in C++
- Minimum Add to Make Parentheses Valid in Python
- Program to find minimum remove required to make valid parentheses in Python
- Program to find minimum number of characters to be added to make it palindrome in Python
- Valid Parentheses in C++
- What least number must be added to 81180 to make it a perfect square?
- Minimum number of elements to be removed to make XOR maximum using C++.
- Find minimum number to be divided to make a number a perfect square in C++
- What should be added to 3a-2b+c to make it a-b+5c
- Longest Valid Parentheses in Python
- Program to count number of minimum swaps required to make it palindrome in Python
- Minimum number of digits required to be removed to make a number divisible by 4
- Minimum number of deletions to make a string palindrome in C++.
- Minimum Number of Steps to Make Two Strings Anagram in C++
- Minimum number of elements that should be removed to make the array good using C++.

Advertisements