- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Bracket Addition in C++
Suppose we have a string s containing only '(' and ')', we have to find the minimum number of brackets that can be inserted to make the string balanced.
So, if the input is like "(()))(", then the output will be 2 as "(()))(", this can be made balanced like "((()))()".
To solve this, we will follow these steps −
:= 0, cnt := 0
for initialize i := 0, when i < size of s, update (increase i by 1), do −
if s[i] is same as '(', then −
(increase o by 1)
Otherwise
if o is non-zero, then −
(decrease o by 1)
Otherwise
(increase cnt by 1)
return cnt + o
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int solve(string s) { int o = 0; int cnt = 0; for(int i = 0; i < s.size(); i++){ if(s[i] == '('){ o++; } else { if(o) o--; else cnt++; } } return cnt + o; } }; int main(){ Solution ob; cout << (ob.solve("(()))(")); }
Input
Input: "(()))("
Output
2
Advertisements