Skip to content

Commit 120cf05

Browse files
authored
Create Minimum_swaps_for_bracket_balancing
This is a greedy problem contribution.
1 parent 8fa6721 commit 120cf05

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
using namespace std;
5+
6+
// Function to calculate swaps required
7+
long swapCount(string s)
8+
{
9+
// Keep track of '['
10+
vector<int> pos;
11+
for (int i = 0; i < s.length(); ++i)
12+
if (s[i] == '[')
13+
pos.push_back(i);
14+
15+
int count = 0; // To count number of encountered '['
16+
int p = 0; // To track position of next '[' in pos
17+
long sum = 0; // To store result
18+
19+
for (int i = 0; i < s.length(); ++i)
20+
{
21+
// Increment count and move p to next position
22+
if (s[i] == '[')
23+
{
24+
++count;
25+
++p;
26+
}
27+
else if (s[i] == ']')
28+
--count;
29+
30+
// We have encountered an unbalanced part of string
31+
if (count < 0)
32+
{
33+
// Increment sum by number of swaps required
34+
// i.e. position of next '[' - current position
35+
sum += pos[p] - i;
36+
swap(s[i], s[pos[p]]);
37+
++p;
38+
39+
// Reset count to 1
40+
count = 1;
41+
}
42+
}
43+
return sum;
44+
}
45+
46+
// Driver code
47+
int main()
48+
{
49+
string s = "[]][][";
50+
cout << swapCount(s) << "\n";
51+
52+
s = "[[][]]";
53+
cout << swapCount(s) << "\n";
54+
return 0;
55+
}

0 commit comments

Comments
 (0)