Given a string of length, N finds the minimum number of characters needed to delete to make right and left shift of the remaining string equal.
Examples :
Input : str: "36363636"
Output : 0
Explanation :
left shift of the input string is "63636363" and the right shift is
"63636363" and both are equal so there is no need to delete any
character form the string.
Input : str: "200210"
Output : 2
Explanation :
left shift and right shift of the entire string are not equal
therefore the deletion is needed.
if we delete the element at the index {2, 5} according to 1 based
indexing then the remaining string "2020" will give left and the right
shift equal.
so we have to delete the two elements.
Approach :
- The main observation here is all the elements at the index i and i + 2 should be the same in the remaining string so the remaining string can only contain two different elements
- To make the max length of elements which have max two different elements check for all the possibilities of the digit less than 2
- Find the maximum length string we can make using the max two different elements
- If both elements are equal then take any length but if both elements are different then take only even length
- Return N – max length
Time Complexity : O( N)
Auxiliary Space : O(1)
Implementation :
#include<bits/stdc++.h>
using namespace std;
int MinNeededDeletion(string s){
// size of the string
int n = s.length();
// initialising the ans
int mxlength = 2;
// taking all the possible combination
for(int i = 0; i <= 9; ++i){
for(int j = 0; j <= 9; ++j){
char ele = i + '0';
int count = 0;
// finding the longest length
// of the string like ijij.....
// possible from the given string
for(int k = 0; k < n; ++k){
if(s[k] == ele){
count++;
ele = (ele == i + '0')? (j + '0') : i + '0';
}
}
// if both the elements are same
// take all the longest string
if(i == j) mxlength = max(mxlength, count);
else {
// only take the even length elements
mxlength = max(mxlength, (count%2 == 0)? count:(count - 1));
}
}
}
return n - mxlength;
}
int main(){
string s = "200210";
cout << MinNeededDeletion(s) << endl;
}
Output : 2