Minimum steps to empty String of ‘a’s and ‘b’s
Last Updated :
31 Aug, 2023
Given a string str consisting of only two characters ‘a‘ and ‘b‘, the task is to find the minimum steps required to make the string empty by removing consecutive a’s and b’s.
Examples:
Input: str = “bbaaabb”
Output: 2
Explanation:
- Operation 1: Removal of all a’s modifies str to “bbbb”.
- Operation 2: Removal of all remaining b’s makes str empty.
- Therefore, the minimum number of operations required is 2.
Input: str = “aababaa”
Output: 3
Explanation:
- Operation 1: Removal of b’s modifies str to “aaabaa”.
- Operation 2: Removal of b’s modifies str = “aaaaa”.
- Operation 3: Removal of all remaining a’s makes str empty.
- Therefore, the minimum number of operations required is 3.
Approach: This can be solved with the following idea:
The given problem can be solved using Greedy Approach. The idea is to use the count of consecutive sequences of the same character.
Below are the steps involved in the implementation of the code:
- Maintain a counter variable named cnt and initialize it with zero.
- Traverse the given string str and whenever the current character is not equal to its previous character increase cnt by 1. Here we are counting the number of consecutive sequences of the same character.
- At the end, the answer will be (cnt/2 + 1).
Below is the implementation of the code:
C++
#include <bits/stdc++.h>
using namespace std;
int minSteps(string str)
{
int cnt = 1;
for ( int i = 1; i < str.size(); i++) {
if (str[i] != str[i - 1]) {
cnt++;
}
}
return cnt / 2 + 1;
}
int main()
{
string str = "aababaa" ;
int ans = minSteps(str);
cout << ans;
return 0;
}
|
Java
import java.util.*;
class GFG {
public static int minSteps(String str)
{
int cnt = 1 ;
for ( int i = 1 ; i < str.length(); i++) {
if (str.charAt(i) != str.charAt(i - 1 )) {
cnt++;
}
}
return cnt / 2 + 1 ;
}
public static void main(String[] args)
{
String str = "aababaa" ;
System.out.println(minSteps(str));
}
}
|
Python3
def minSteps(string):
cnt = 1
for i in range ( 1 , len (string)):
if string[i] ! = string[i - 1 ]:
cnt + = 1
return cnt / / 2 + 1
if __name__ = = '__main__' :
string = "aababaa"
ans = minSteps(string)
print (ans)
|
C#
using System;
class GFG
{
public static int minSteps( string str)
{
int cnt = 1;
for ( int i = 1; i < str.Length; i++)
{
if (str[i] != str[i - 1])
{
cnt++;
}
}
return cnt / 2 + 1;
}
public static void Main( string [] args)
{
string str = "aababaa" ;
Console.WriteLine(minSteps(str));
}
}
|
Javascript
function minSteps(str) {
let cnt = 1;
for (let i = 1; i < str.length; i++) {
if (str[i] !== str[i - 1]) {
cnt++;
}
}
return Math.floor(cnt / 2) + 1;
}
let str = "aababaa" ;
let ans = minSteps(str);
console.log(ans);
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...