Java Program for Minimum Move to end Operations to Make all Strings Equal


In this problem, we have given n strings and need to make all strings equal by rotating them.

To solve the problem, we need to pick any string from the array and need make all strings equal by rotating them. Also, we need to count the total number of required operations to rotate all strings. We can pick each string one by one, make all other strings equal, count the total operations for each string, and take a minimum of them.

Problem statement − We have given an array containing n strings. All strings are permutations of each other. We need to count the total number of minimum operations required to make all strings equal by making left rotations of the string.

Sample examples

Input

array[] = { "abcd", "abcd", "dabc", "bcda" }

Output

4

Explanation − We can make all strings equal to ‘abcd’. So, we need 1 operation to convert ‘dabc’ to ‘abcd’ and 3 operations to convert ‘bcda’ to ‘abcd’.

Input

 array = {‘pq’, ‘pq’, ‘pq’}

Output

0

Explanation − All strings are equal. So, we don’t need to perform any operation.

Input

 array = {‘ab’, ‘bd’, ‘cd’}

Output

-1

Explanation − The given strings are not permutations of each other. So, print −1.

Approach 1

In this approach, we will traverse the array of strings. We will pick one string and make all strings equal to the particular string by rotating them. Also, we count operations for each string and take minimum operations.

Here, we use the queue data structure to count the minimum number of rotations to make two strings equal.

Algorithm

Step 1 − Initialize the ‘output’ with the maximum value.

Step 2 − Start traversing the array.

Step 3 − Initialize the ‘curr_operations’ variable with zero to store the total rotations required to make all strings equal to the string at the pth index.

Step 4 − Use the nested loop to traverse the array again. In the loop, execute the isRotation() function by passing the array[p] and array[q] string as parameters to count the total required rotation to make array[q] equal to array[p].

Step 4.1 − In the isRotation() function, if the length of both strings is not equal, return −1.

Step 4.2 − If both strings are equal, return 0.

Step 4.3 − Create an ‘alpha2Queue’ queue and store all the characters of the alpha2 string in it.

Step 4.4 − Create an ‘alpha1Queue’ queue and store all characters of an alpha string in that.

Step 4.5 − Initialize the ‘k’ with 0 to store the total number of rotations. Use a while loop to make iterations.

Step 4.6− In each iteration, remove the character from the ‘alpha1Queue’ and push at the end. After that, match both queues. If both queues are equal, return the value of K.

Step 4.7 − Return −1 at the end of the function.

Step 5 − If the returned value from the isRotation() function is −1, return −1. Otherwise, add the index value to the ‘curr_operations’ variable.

Step 7 − Use the Math.min() method to get minimum value from output and curr_operations and store it in the output variable.

Step 8 − Return output value.

Example

import java.util.*;
public class Main {
    // function to find total number of operations to get alpha string from alpha2
    public static int isRotation(String alpha, String alpha2) {
        // base case
        if (alpha.length() != alpha2.length())
            return -1;
        if (alpha.equals(alpha2))
            return 0;
        Queue<Character> alpha2Queue = new LinkedList<>();
        // push all characters of alpha2 to queue
        for (int i = 0; i < alpha2.length(); i++) {
            alpha2Queue.add(alpha2.charAt(i));
        }
        // Push all characters of alpha to queue
        Queue<Character> alpha1Queue = new LinkedList<>();
        for (int i = 0; i < alpha.length(); i++) {
            alpha1Queue.add(alpha.charAt(i));
        }
        int k = 0;
        while (k < alpha.length()) {
            k++;
            char ch = alpha1Queue.peek(); 
            alpha1Queue.remove(); // deque
            alpha1Queue.add(ch); // enque
            // queue matching
            if (alpha1Queue.equals(alpha2Queue))
                return k;
        }
        return -1;
    }
    static int minOperations(String array[], int len) {
        int output = Integer.MAX_VALUE; // to store minimum operations
        for (int p = 0; p < len; p++) {
            // to store operations for the current iteration
            int curr_operations = 0;
            // total number of rotations required to make all strings of the array equal to
            // str[i]
            String temp = "";
            for (int q = 0; q < len; q++) {
                int index = isRotation(array[p], array[q]);
                // return -1, if array[q] is not a rotation of array[p]
                if (index == -1)
                    return -1;
                // update curr_operations
                curr_operations += index;
            }
            // get minimum operations
            output = Math.min(curr_operations, output);
        }
        return output;
    }
    // Driver code
    public static void main(String args[]) {
        String array[] = { "abcd", "abcd", "dabc", "bcda" };
        int len = array.length;
        System.out.println(
                "The minimum operations required to make all strings of the array equal is "
                        + minOperations(array, len));
    }
}

Output

The minimum operations required to make all strings of the array equal is 4

Time complexity− O(N*N*K), where O(N*N) is to traverse the array and O(K) is to traverse the string.

Space complexity − O(K) as we use a queue to store the string characters.

Approach 2

We will use the ‘+’ operator to merge the string in this approach. After that, we will use the indeOf() method to find the index of the goal string in the merged string.

Algorithm

Step 1 − Initialize the ‘output’ variable with max value and start traversing the array.

Step 2 − Initialize the ‘curr_operations’ with zero and use another nested loop to traverse the array.

Step 3 − In the temp string, store the value of array[q] + array[q].

Step 4 − Use the indexOf() method to find the index of array[p] into the ‘temp’ string.

Step 5 − If the index is equal to the length of the temp string, return −1.

Step 6 − Add index value to the ‘curr_operations’.

Step 7 − Store the minimum from output and curr_operations into the output.

Step 8 − Return output.

Example

import java.util.*;

public class Main {
    static int minOperations(String array[], int len) {
        // to store minimum operations
        int output = Integer.MAX_VALUE;
        for (int p = 0; p < len; p++) {
            // to store operations for the current iteration
            int curr_operations = 0;
            // total number of rotations required to make all strings of the array equal to
            // str[i]
            String temp = "";
            for (int q = 0; q < len; q++) {
                // Concatenating string to itself to check whether it is a rotation of arr[i]
                temp = array[q] + array[q];
                // find index of array[p] in temp
                int index = temp.indexOf(array[p]);
                // return -1, if array[q] is not a rotation of array[p]
                if (index == array[p].length())
                    return -1;
                // update curr_operations
                curr_operations += index;
            }
            // get minimum operations
            output = Math.min(curr_operations, output);
        }
        return output;
    }
    public static void main(String args[]) {
        String array[] = { "abcd", "abcd", "dabc", "bcda" };
        int len = array.length;
        System.out.println(
                "The minimum operations required to make all strings of the array equal is " + minOperations(array, len));
    }
}

Output

The minimum operations required to make all strings of the array equal is 4

Time complexity− O(N*N*K), as we use the indexOf() method in two nested loops.

Space complexity − O(1) as we don’t use extra space.

The second approach is more space optimized than the first approach. Also, the code of the second approach is more readable than the first approach. Programmers can also use other approaches to make rotational strings same to solve the problem.

Updated on: 14-Aug-2023

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements