Java Program to Minimize Characters to be changed to make the Left and Right Rotation of a String Same


In this problem, we need to change the minimum characters in the given string to make its left and right rotations the same. In the string, we can observe that we can only make the left and right rotations of the string same if the string has an odd length and all characters are same, or the string has an even length and characters at even and odd indexes the same.

For example,

  • abab – Left and right rotation of the string is baba and baba.

  • aaa – Left and right rotation of the stirng is aaa and aaa.

  • abc – The left and right rotation of the string is bca and cab, respectively.

  • aabb – The left and right rotation of the string is abba and baab.

Problem statement – We have given a string str containing the alphabetical characters. The size of the string is equal to the N. We need to change the minimum number of characters to make the left and right rotations of the string.

Sample examples

Input

str = "tuto"

Output

1

Explanation – We either need to change ‘u’ -> ‘o’ or ‘o’ -> ‘u’ to make left and right rotations of the string same.

Input

str = "abcde";

Output

4

Explanation – We need to make all characters the same as string length is odd to make left and right rotations same.

Input

str = ‘mnmnmnmnmnmn’

Output

0

Explanation – The left and right rotations of the string is already same.

Approach 1

In this approach, we will implement the logic based on the observation we discussed above. If the string length is odd, we will calculate the minimum cost to make all characters equal, and if the string length is even, we will calculate the minimum cost to make all characters equal at the even and odd index of the string.

Algorithm

Step 1 – Store the length of the string in the ‘len’ variable. Also, initialize the ‘min_chars’ with the string length as we assume that initially, all characters of the string are different.

Step 2 – If the string length is even, follow the below steps.

Step 2.1 – Define the ‘evenPosFreq’ and ‘oddPosFreq’ array of length 128 to store the frequency of each character in the given string.

Step 2.2 – Start traversing the string, and ‘p’ is even, increment the value by 1 in the ‘evenPosFreq’ array at the index equal to the character’s ASCII value. Else, increment the value by 1 in the ‘oddPosFreq’ array.

Step 2.3 – Now, we need to find the maximum frequency of any character at the even and odd positions.

Step 2.4 – Define the ‘MaxFreqEven’ and ‘MaxFreqOdd’ variables and initialize with zero. Also, start traversing the frequency array, get the maximum value from both arrays, and store it in the ‘MaxFreqEven’ and ‘MaxFreqOdd’ variables.

Step 2.5 – In the min_chars variable, store the resultant value after subtracting the value of ‘MaxFreqEven’ and ‘MaxFreqOdd’ from the string length.

Step 3 – If the string length is odd, follow the below steps.

Step 3.1 – Define the ‘allCharFreq’ array to store the frequency of each character. Also, store the frequency of each character into that by traversing the string.

Step 3.2 – Define the maxChar variable to store characters with maximum frequency. Traverse the array and find the maximum element in the array.

Step 3.3 - In the min_chars variable, store the resultant value after subtracting the maxChars from the string length.

Step 4 – Return the value of the min_chars variable.

Example

public class TP {
    public static int findMinCharRemoval(String alpha) {
        int len = alpha.length();
        // Initially, let's say we need to remove all characters
        int min_chars = len;
        // For the odd length of the string
        if (len % 2 == 0) {
            // Defining array to store the frequency
            int[] evenPosFreq = new int[128];
            int[] oddPosFreq = new int[128];
            // Traverse the string
            for (int p = 0; p < len; p++) {
                // Update character frequency in the array based on the odd or even index
                if (p % 2 == 0) {
                    evenPosFreq[alpha.charAt(p)]++;
                } else {
                    oddPosFreq[alpha.charAt(p)]++;
                }
            }
            // to store max frequency of any character at even and odd positions
            int MaxFreqEven = 0, MaxFreqOdd = 0;
            // Find the maximum frequency
            for (char c = 'a'; c <= 'z'; c++) {
                MaxFreqEven = Math.max(MaxFreqEven, evenPosFreq[c]);
                MaxFreqOdd = Math.max(MaxFreqOdd, oddPosFreq[c]);
            }
            // Final result
            min_chars = min_chars - MaxFreqEven - MaxFreqOdd;
        }
        // For odd string
        else {
            // Get frequncy of all chars
            int[] allCharFreq = new int[128];
            for (int p = 0; p < len; p++) {
                allCharFreq[alpha.charAt(p)]++;
            }
            // Finding the most occurring character
            int maxChar = 0;
            for (char c = 'a'; c <= 'z'; c++) {
                maxChar = Math.max(maxChar, allCharFreq[c]);
            }
            // Final answer
            min_chars = min_chars - maxChar;
        }
        // return final answer
        return min_chars;
    }
    public static void main(String[] args) {
        String str = "tuto";
        System.out.print("The minimum numbers of character we should remove to get left and right rotation of string same is - "
                        + findMinCharRemoval(str));
    }
}

Output

The minimum numbers of character we should remove to get left and right rotation of string same is - 1

Time complexity – O(N) as we traverse the string multiple times.

Space complexity – O(1) as we use the constant space to store the frequency of string characters.

We learned to make left and right rotations of the string the same in Java. Programmers can also try to find the left and right rotation of the given string for more practice.

Updated on: 25-Aug-2023

64 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements