Minimize characters to be changed to make the left and right rotation of a string same

Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same.

Examples:

Input: S = “abcd”
Output: 2
Explanation:
String after the left shift: “bcda”
String after the right shift: “dabc”
Changing the character at position 3 to ‘a’ and character at position 4 to ‘b’, the string is modified to “abab”.
Therefore, both the left and right rotations becomes “baba”.

Input: S = “gfg”
Output: 1
Explanation:
After updating the character at position 1 to ‘g’, the string becomes “ggg”.
Therefore, the left and right rotation are equal.

Approach: The key observation to solve the problem is that when the length of the string is even, then all the characters at even index and characters at odd index must be the same for the left and right rotations to be the same. For strings of odd length, all the characters must be equal. Follow the steps below to solve the problem:



  • Check if the length of the string is even, then the minimum number of characters to be changed is the length of the string excluding the frequency of the most occurring element at the even indices and odd indices.
  • Otherwise, if the length of the string is odd, then the minimum number of characters to be changed is the length of the string excluding the frequency of the most occurring character in the string.
  • Print the final count obtained.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program of the
// above approch
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum
// characters to be removed from
// the string
int getMinimumRemoval(string str)
{
    int n = str.length();
 
    // Initialize answer by N
    int ans = n;
 
    // If length is even
    if (n % 2 == 0) {
 
        // Frequency array for odd
        // and even indices
        vector<int> freqEven(128);
        vector<int> freqOdd(128);
 
        // Store the frequency of the
        // characters at even and odd
        // indices
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                freqEven[str[i]]++;
            }
            else {
                freqOdd[str[i]]++;
            }
        }
 
        // Stores the most occuring frequency
        // for even and odd indices
        int evenMax = 0, oddMax = 0;
 
        for (char chr = 'a'; chr <= 'z'; chr++) {
 
            evenMax = max(evenMax, freqEven[chr]);
            oddMax = max(oddMax, freqOdd[chr]);
        }
 
        // Update the answer
        ans = ans - evenMax - oddMax;
    }
 
    // If length is odd
    else {
        // Stores the frequency of the
        // characters of the string
        vector<int> freq(128);
        for (int i = 0; i < n; i++) {
            freq[str[i]]++;
        }
 
        // Stores the most occuring character
        // in the string
        int strMax = 0;
        for (char chr = 'a'; chr <= 'z'; chr++) {
            strMax = max(strMax, freq[chr]);
        }
 
        // Update the answer
        ans = ans - strMax;
    }
 
    return ans;
}
 
// Driver Code
int main()
{
    string str = "geeksgeeks";
 
    cout << getMinimumRemoval(str);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program of the
// above approch
class GFG{
     
// Function to find the minimum
// characters to be removed from
// the string
public static int getMinimumRemoval(String str)
{
    int n = str.length();
 
    // Initialize answer by N
    int ans = n;
 
    // If length is even
    if (n % 2 == 0)
    {
 
        // Frequency array for odd
        // and even indices
        int[] freqEven = new int[128];
        int[] freqOdd = new int[128];
 
        // Store the frequency of the
        // characters at even and odd
        // indices
        for(int i = 0; i < n; i++)
        {
            if (i % 2 == 0)
            {
                freqEven[str.charAt(i)]++;
            }
            else
            {
                freqOdd[str.charAt(i)]++;
            }
        }
 
        // Stores the most occuring frequency
        // for even and odd indices
        int evenMax = 0, oddMax = 0;
 
        for(char chr = 'a'; chr <= 'z'; chr++)
        {
            evenMax = Math.max(evenMax,
                               freqEven[chr]);
            oddMax = Math.max(oddMax,
                              freqOdd[chr]);
        }
 
        // Update the answer
        ans = ans - evenMax - oddMax;
    }
 
    // If length is odd
    else
    {
         
        // Stores the frequency of the
        // characters of the string
        int[] freq = new int[128];
        for(int i = 0; i < n; i++)
        {
            freq[str.charAt(i)]++;
        }
 
        // Stores the most occuring character
        // in the string
        int strMax = 0;
        for(char chr = 'a'; chr <= 'z'; chr++)
        {
            strMax = Math.max(strMax, freq[chr]);
        }
         
        // Update the answer
        ans = ans - strMax;
    }
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    String str = "geeksgeeks";
     
    System.out.print(getMinimumRemoval(str));
}
}
 
// This code is contributed by divyeshrabadiya07

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program of the
# above approch
 
# Function to find the minimum
# characters to be removed from
# the string
def getMinimumRemoval(str):
   
    n = len(str)
 
    # Initialize answer by N
    ans = n
 
    # If length is even
    if(n % 2 == 0):
 
        # Frequency array for odd
        # and even indices
        freqEven = {}
        freqOdd = {}
        for ch in range(ord('a'),
                        ord('z') + 1):
            freqEven[chr(ch)] = 0
            freqOdd[chr(ch)] = 0
 
        # Store the frequency of the
        # characters at even and odd
        # indices
        for i in range(n):
            if(i % 2 == 0):
                if str[i] in freqEven:
                    freqEven[str[i]] += 1
            else:
                if str[i] in freqOdd:
                    freqOdd[str[i]] += 1
 
        # Stores the most occuring
        # frequency for even and
        # odd indices
        evenMax = 0
        oddMax = 0
 
        for ch in range(ord('a'),
                        ord('z') + 1):
            evenMax = max(evenMax,
                      freqEven[chr(ch)])
            oddMax = max(oddMax,
                     freqOdd[chr(ch)])
 
        # Update the answer
        ans = ans - evenMax - oddMax
 
    # If length is odd
    else:
 
        # Stores the frequency of the
        # characters of the string
        freq = {}
         
        for ch in range('a','z'):
            freq[chr(ch)] = 0
        for i in range(n):
            if str[i] in freq:
                freq[str[i]] += 1
 
        # Stores the most occuring
        # characterin the string
        strMax = 0
         
        for ch in range('a','z'):
            strMax = max(strMax,
                     freq[chr(ch)])
 
        # Update the answer
        ans = ans - strMax
 
    return ans
 
# Driver Code
str = "geeksgeeks"
print(getMinimumRemoval(str))
 
# This code is contributed by avanitrachhadiya2155

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program of the
// above approch
using System;
class GFG{
     
// Function to find the minimum
// characters to be removed from
// the string
public static int getMinimumRemoval(String str)
{
  int n = str.Length;
 
  // Initialize answer by N
  int ans = n;
 
  // If length is even
  if (n % 2 == 0)
  {
    // Frequency array for odd
    // and even indices
    int[] freqEven = new int[128];
    int[] freqOdd = new int[128];
 
    // Store the frequency of the
    // characters at even and odd
    // indices
    for(int i = 0; i < n; i++)
    {
      if (i % 2 == 0)
      {
        freqEven[str[i]]++;
      }
      else
      {
        freqOdd[str[i]]++;
      }
    }
 
    // Stores the most occuring frequency
    // for even and odd indices
    int evenMax = 0, oddMax = 0;
 
    for(char chr = 'a'; chr <= 'z'; chr++)
    {
      evenMax = Math.Max(evenMax,
                         freqEven[chr]);
      oddMax = Math.Max(oddMax,
                        freqOdd[chr]);
    }
 
    // Update the answer
    ans = ans - evenMax - oddMax;
  }
 
  // If length is odd
  else
  {
    // Stores the frequency of the
    // characters of the string
    int[] freq = new int[128];
    for(int i = 0; i < n; i++)
    {
      freq[str[i]]++;
    }
 
    // Stores the most occuring character
    // in the string
    int strMax = 0;
    for(char chr = 'a'; chr <= 'z'; chr++)
    {
      strMax = Math.Max(strMax, freq[chr]);
    }
 
    // Update the answer
    ans = ans - strMax;
  }
  return ans;
}
 
// Driver code
public static void Main(String[] args)
{
  String str = "geeksgeeks";
  Console.Write(getMinimumRemoval(str));
}
}
 
// This code is contributed by Rajput-Ji

chevron_right


Output: 

6






Time Complexity: O(N) 
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.