Minimum circular rotations to obtain a given numeric string by avoiding a set of given strings


In this problem, we will find the number of rotations required to achieve the target string from the string containing N 0s. Also, we will skip the strings given in the array while making rotations.

We can use the BFS algorithm to find the minimum rotations required to get the target string.

Problem Statement

We have given a target string containing the N numeric characters. Also, we have given the strs[] array containing the M strings of size N containing the numeric characters. We need to initially achieve the target string from a string containing N 0's by performing the given operation multiple times. In a single operation, we can rotate any character of the string, but we need to ensure that in any rotation, we shouldn't get the string that strs[] contains. We need to find the minimum number of rotations required to get the target string from the initial string.

Note − We can make 9 to 0 and 0 to 9 for rotation.

Sample Examples

Input

N = 4; target = "7531"; strs = {"1543", "7434", "7300", "7321", "2427"};

Output

12

Explanation

We need to start from the 0000 string. After that, we can make the below rotations and skip the string the array contains while rotating the string.

  • 0000 → 9000 → 8000 → 7000 → 7900 → 7800 → 7700 → 7600 → 7500 → 7510 → 7520 → 7530 → 7531

Here, we have skipped the 7300 string. The other solution can be as shown below.

  • 0000 → 9000 → 8000 → 7000 → 7100 → 7200 → 7210 → 7310 → 7410 → 7510 → 7520 → 7530 → 7531

Input

N = 4; target = "7531"; strs = {"7513", "7434", "7300", "7321", "2427"};

Output

-1

Explanation

The target string exists in the array, and we need to skip all strings that the array contains. So, achieving the target string in any case is not possible.

Approach

In this approach, we will rotate each character of the given string in the forward and reverse direction. After that, we will insert the updated string into the queue. In the next iteration, we will take all strings from the previous iteration, update them, and insert them into the queue.

While updating the string, we will make sure to skip the strings of the strs[] array. When we get the target string, we will return the total number of required rotations.

Algorithm

  • Step 1 − Initialize the target_str with N 0's. We will update the target_str string to get the target string.

  • Step 2 − Also, define the 'skip' set to store strings that we need to skip. So, insert all strings of strs[] into the set.

  • Step 3 − If the skip set contains the target_str or target string, return -1.

  • Step 4 − Define the queue of strings and insert the target_str string into the queue. Also, define the 'rotations' to store the number of rotations.

  • Step 5 − Traverse the queue.

  • Step 5.1 − Increment the rotations and get the length of the queue.

  • Step 5.2 − Use the for loop to traverse all elements of the queue.

  • Step 5.2.1 − Get the front element from the queue, and store it in the 'str' string variable.

  • Step 5.2.2 − Traverse each character of the 'str' string.

  • Step 5.2.3 − Store the str[p] into the character 'c' and increment the str[p] by 1. If str[p] is greater than '9', update it to '0'.

  • Step 5.2.4 − If the current string is a target string, return rotations.

  • Step 5.2.5 − If str is not exist in the 'skip' set, push it into the queue. Also, insert str into the skip set as we already visited it. So, we need to skip it next time.

  • Step 5.2.6 − Initialize the str[p] with c − 1. If str[p] becomes less than '0', update it with '9'.

  • Step 5.2.7 − If updated str is equal to target, return rotations. Otherwise, insert str into the que if it is not available in the set.

  • Step 5.2.8 − Insert str into the 'skip' set.

  • Step 5.2.9 − Update str[p] with c, which is the original character.

  • Step 6 − Return -1, when getting target string is not possible.

Example

#include <bits/stdc++.h>
using namespace std;

int minRotations(string target, vector<string> &strs, int N) {
   string target_str = "";
   // Create a string containing N '0'
   for (int p = 0; p < N; p++) {
      target_str += '0';
   }
   unordered_set<string> skip;
   // Insert given string in the set
   for (int p = 0; p < strs.size(); p++)
      skip.insert(strs[p]);
   // Base case
   if (skip.find(target_str) != skip.end())
      return -1;
   if (skip.find(target) != skip.end())
      return -1;
   queue<string> que;
   que.push(target_str);
   // To store a number of rotations
   int rotations = 0;
   // BFS algorithm
   while (!que.empty()) {
      rotations++;
      int len = que.size();
      for (int q = 0; q < len; q++) {
         string str = que.front();
         que.pop();
         // Traverse the string
         for (int p = 0; p < N; p++) {
            char c = str[p];
            // INcrement the character
            str[p]++;
            // Rotate the character
            if (str[p] > '9')
               str[p] = '0';
            // If we got the targeted string
            if (str == target)
               return rotations;
            // When we don't need to skip the string
            if (skip.find(str) == skip.end())
               que.push(str);
            // Add in the set to skip as we already visited
            skip.insert(str);
            // Do the same thing after decreasing the current character by 1
            str[p] = c - 1;
            if (str[p] < '0')
               str[p] = '9';
            if (str == target)
               return rotations;
            if (skip.find(str) == skip.end())
               que.push(str);
            skip.insert(str);
            str[p] = c;
         }
      }
   }
   return -1;
}
int main() {
   int N = 4;
   string target = "7531";
   vector<string> strs = {"1543", "7434", "7300", "7321", "2427"};
   cout << "The minimum rotations required to get the target string is - " << minRotations(target, strs, N) << endl;
   return 0;
}

Output

The minimum rotations required to get the target string is - 12
  • Time complexity − O(N*N*N)

  • Space complexity − O(N)

Conclusion

We used the set to track the visited strings and queue to store the updated string. In each rotation, we update the string we get from the previous iteration. Whenever we find the target string for the first time, we return the count of rotations, as the BFS algorithm always provides the minimum path value.

Updated on: 25-Aug-2023

50 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements