Skip to content
Related Articles

Related Articles

Minimum rotations required to delete both Strings

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 01 Dec, 2022
Improve Article
Save Article

Given two strings A and B which are permutations of each other. The task is to find the minimum number of rotations required to delete both strings completely. We can delete the first characters of both strings if they are the same. Otherwise, the string is rotated one position to left.

Examples:

Input: A = “abcd”,  B = “bcda”
Output: 1
Explanation: rotate A, only one left rotation is required to make both strings equal

Input: A=”geek” B=”geek”
Output : 0
Explanation: Both strings are equal hence the number of operations is 0.

Approach:

The basic idea is to check if A is and B are rotations of each other or not.

  1. Initialize rotations = 0 (Count of rotations)
  2. Check whether the first character of both strings are same or not.
    • If not, then apply left rotation on string A and increment rotations.
    • If the first characters are the same, delete the first character of both strings.
  3. Check whether both strings are empty.
    • If yes then break the loop.
    • Else go to step 2 and repeat it from the next index.

Below is the Implementation of the above approach.

C++14




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to perform left rotation
string leftrotate(string& s, int d)
{
    reverse(s.begin(), s.begin() + d);
    reverse(s.begin() + d, s.end());
    reverse(s.begin(), s.end());
    return s;
}
 
// Function to find the minimum number of rotations
int MinimumRotations(string A, string B)
{
    int rotations = 0;
    int len = A.length();
    int B_index = 0;
    for (int i = 0; i < len; i++) {
 
        // Character removal if first character is same
        if (A[0] == B[B_index]) {
            A.erase(A.begin() + 0);
            B_index++;
        }
 
        // Left rotation if its not same
        if (A[0] != B[B_index]) {
            A = leftrotate(A, 1);
            rotations++;
            i = 0;
        }
    }
 
    // Return final rotations required
    return rotations;
}
 
// Driver code
int main()
{
    string A = "geek";
    string B = "geek";
    cout << MinimumRotations(A, B) << endl;
 
    string A2 = "abcd";
    string B2 = "bcda";
    cout << MinimumRotations(A2, B2) << endl;
 
    string A3 = "agef";
    string B3 = "afge";
    cout << MinimumRotations(A3, B3) << endl;
 
    return 0;
}

Output

0
1
2

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

Approach using Queue:

We can solve this problem using queue for clockwise rotation. We will append characters of string A in queue and iterate over string B. And apply left rotation on queue if required. Else remove the first character from B and pop the queue front from the queue. 

  • Initialize a variable (say rotations) to store the number of rotations required.
  • Create a char queue to store the characters.
    • Append all characters of string A in the queue.
  • Start iteration over string B and check whether the first character of both strings is the same or not.
    • If they are the same then delete the string.
    • Otherwise, rotation is required.
  • Calculate the rotations:
    • Create a variable (say times) to count the number of clockwise rotations.
    • Start a while loop and check if the first elements are not equal. If so, increment times variable and push the frontmost value in the queue and pop() the queue.
    • Return the times variable.
  • Return the rotations variable as the result.

Below is the Implementation of the above approach.

C++14




/*C++ program to determine minimum number
of rotations required to delete both strings*/
 
#include <bits/stdc++.h>
using namespace std;
 
// Clockwise rotation if characters are not same
int ClockwiseRotation(queue<char>& q, char t)
{
    // Initialize times to count number of clockwise rotations done
    int times = 0;
    while (q.front() != t) {
        times++;
        q.push(q.front());
        q.pop();
    }
    return times;
}
 
int MinimumRotations(string A, string B)
{
    // Initialize rotations for storing the total count
    int rotations = 0;
    queue<char> q;
    // Appending all the characters of A in queue
    for (int i = 0; i < A.size(); i++) {
        q.push(A[i]);
    }
    // Iterating on string B
    for (int i = 0; i < B.size(); i++) {
        // If first character is not same hence rotation is required
        if (B[i] != q.front()) {
            rotations += ClockwiseRotation(q, B[i]);
        }
        q.pop();
    }
    // Return final answer
    return rotations;
}
 
// Driver code
int main()
{
    string A = "geek";
    string B = "geek";
    cout << MinimumRotations(A, B) << endl;
 
    string A2 = "abcd";
    string B2 = "bcda";
    cout << MinimumRotations(A2, B2) << endl;
 
    string A3 = "agef";
    string B3 = "afge";
    cout << MinimumRotations(A3, B3) << endl;
 
    return 0;
}

Java




// java implementation
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
 
class GFG
{
   
  // Clockwise rotation if characters are not same
  public static int ClockwiseRotation(Queue<Character> q,
                                      char t)
  {
     
    // Initialize times to count number of clockwise
    // rotations done
    int times = 0;
    while (q.peek() != t) {
      times++;
      q.add(q.peek());
      q.remove();
    }
    return times;
  }
 
  public static int MinimumRotations(String A, String B)
  {
     
    // Initialize rotations for storing the total count
    int rotations = 0;
    Queue<Character> q = new LinkedList<Character>();
     
    // Appending all the characters of A in queue
    for (int i = 0; i < A.length(); i++) {
      q.add(A.charAt(i));
    }
     
    // Iterating on string B
    for (int i = 0; i < B.length(); i++)
    {
       
      // If first character is not same hence rotation
      // is required
      if (B.charAt(i) != q.peek()) {
        rotations
          += ClockwiseRotation(q, B.charAt(i));
      }
      q.remove();
    }
     
    // Return final answer
    return rotations;
  }
 
  public static void main(String[] args)
  {
    String A = "geek";
    String B = "geek";
    System.out.println(
      MinimumRotations(A, B));
 
    String A2 = "abcd";
    String B2 = "bcda";
    System.out.println(
      MinimumRotations(A2, B2));
 
    String A3 = "agef";
    String B3 = "afge";
    System.out.println(
      MinimumRotations(A3, B3));
  }
}
 
// This code is contributed by ksam24000

Output

0
1
2

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

Related Articles:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!