Minimum deletions to make left and right shift of a string equal

Updated

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 :

  1. 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
  2. To make the max length of elements which have max two different elements check for all the possibilities of the digit less than 2
  3. Find the maximum length string we can make using the max two different elements
  4. If both elements are equal then take any length but if both elements are different then take only even length
  5. 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

Comment
Next tutorial
Mithlesh Upadhyay Published 1 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials