Skip to content

Commit fd0f4b7

Browse files
Commit solution with explanation
1 parent 7395619 commit fd0f4b7

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
Intuition
2+
Basically, the problem asks you to have all a before b in string s by deleting minimum number of characters from string s.
3+
The intuition is simple enough. We just need to store how many b come before a at a specific position i in string s.
4+
This will tell us how many a we have to delete which come after b or how many b we have to delete which come before a.
5+
In the end, we will count the minimum number of deletions we have to make in order to achieve the string with all a before b.
6+
Approach
7+
Create a prefix_b array to store all b from left to right and create a suffix_a array to store all a from right to left.
8+
Now, at every index i check how many prefix b and suffix a we have to delete by adding prefix_b[i] and suffix_a[i].
9+
Keep the track of minimum deletions using a variable mini which will be our final answer to return.
10+
Complexity
11+
Time complexity: O(n)
12+
Space complexity: O(n)

212-30th_July-Min_deletions/code.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution
2+
{
3+
public:
4+
int minimumDeletions(string s)
5+
{
6+
vector<int> prefix_b(s.size() + 2, 0), suffix_a(s.size() + 2, 0);
7+
prefix_b[0] = 0;
8+
suffix_a[suffix_a.size() - 1] = 0;
9+
10+
for (int i = 1; i < prefix_b.size() - 1; i++)
11+
{
12+
if (s[i - 1] == 'b')
13+
{
14+
prefix_b[i + 1] = prefix_b[i] + 1;
15+
}
16+
else
17+
{
18+
prefix_b[i + 1] = prefix_b[i] + 0;
19+
}
20+
}
21+
22+
for (int i = s.size(); i >= 1; i--)
23+
{
24+
if (s[i - 1] == 'a')
25+
{
26+
suffix_a[i - 1] = suffix_a[i] + 1;
27+
}
28+
else
29+
{
30+
suffix_a[i - 1] = suffix_a[i] + 0;
31+
}
32+
}
33+
34+
int mini = INT_MAX;
35+
36+
for (int i = 0; i < s.size() + 2; i++)
37+
{
38+
mini = min(prefix_b[i] + suffix_a[i], mini);
39+
}
40+
41+
return mini;
42+
}
43+
};

0 commit comments

Comments
 (0)