Python Program to find minimum number of rotations to obtain actual string?


Understanding how to effectively handle strings is a fundamental programming task that can considerably enhance the performance of our code. Finding the least amount of rotations necessary to produce the desired string from a rotated string is an intriguing challenge in string manipulation. Situations like text processing, cryptography, and data compression frequently involve this issue.

Consider the scenario in which a string is rotated a certain amount to the right. Finding the fewest rotations necessary to transform the string back into its original form is the objective. We can learn more about the string's structure and get access to useful information by finding a solution to this problem.

This article will examine two methods for determining the fewest number of rotations necessary to return the original string from a rotated string. Python, a flexible and well-liked programming language recognized for its readability and simplicity of use, will be used to put these techniques into practice.

Approaches

To search for a minimum number of rotations to obtain an actual string in Python, we can follow the two methods −

  • Utilizing the Brute Force.

  • Utilizing the while loop in a user-defined function.

Let us investigate both approaches −

Approach-1: Utilizing the Brute Force

The first string is rotated by all conceivable locations in the brute force method, and the second string is then compared to the rotated first string. We maintain track of the minimal number of rotations necessary to obtain the second string by iterating over all feasible rotations. After the loop, if the minimum rotations variable is still infinite, it is impossible to acquire the second string by rotating the first string. If not, we return the bare minimum of needed rotations. The temporal complexity of this method is O(n^2), where n is the length of the first string.

Algorithm

The steps to search a minimum number of rotations to obtain the actual string in Python are as follows −

Step 1 − Create a function with two strings as its input.

Step 2 − Create a variable with the initial value of infinity to track the very minimum number of rotations necessary.

Step 3 − From 0 to the length of the first string, iterate over the possible values.

Step 4 − The first string should be rotated by the current index places. This verifies that the second string and the rotated string are equal. If so, change the variable's value to the lowest value that falls between the current minimum and the current index.

Step 5 − Return -1 (signifying that it is not feasible to retrieve the second string by rotating the first string) if the minimum rotations variable is still set to infinity.

Step 6 − Return the minimal rotations variable if not.

Example

def min_rotations_bf(s1, s2):
   min_rotations = float('inf')

   for i in range(len(s1)):
      rotated = s1[i:] + s1[:i]
      if rotated == s2:
         min_rotations = min(min_rotations, i)

   if min_rotations == float('inf'):
      return -1
   else:
      return min_rotations


# Example usage
s1 = "program"
s2 = "grampro"
bf_result = min_rotations_bf(s1, s2)

print("String 1:", s1)
print("String 2:", s2)
print("Minimum rotations (Brute Force):", bf_result)

Output

String 1: program
String 2: grampro
Minimum rotations (Brute Force): 3

Approach-2: Utilizing the while loop in a user-defined function

The effective method uses a concatenated string to verify the presence of the second string rather than doing explicit string rotations. We return -1 if it is impossible to retrieve the second string through rotations of the first string due to the differing lengths of the two strings. We can figure out how many rotations are necessary to separate the second string from the first string by determining whether the second string is a substring of the concatenated string. To determine the least number of rotations, if the second string is discovered as a substring, we compute the index and divide it by the length of the first string. The time complexity of this method is O(n), where n is the length of the first string.

Algorithm

The steps to search a minimum number of rotations to obtain the actual string in Python are as follows −

Step 1 − Create a function with two strings as its input.

Step 2 − Return -1 if the lengths of the two strings are not equal (because the second string cannot be obtained by rotating the first string).

Step 3 − Create a temporary string by concatenating the first string with itself.

Step 4 − Return the lowest number of rotations necessary as the index of the second string in the temporary string divided by the length of the first string if the second string is a substring of the temporary string.

Step-5− If not, return -1.

Example

def min_rotations_efficient(s1, s2):
   if len(s1) != len(s2):
      return -1

   rotations = 0
   n = len(s1)

   # Check for left rotations
   while rotations < n:
      if s1 == s2:
         return rotations
      s1 = s1[1:] + s1[0]
      rotations += 1

   # Check for right rotations
   s1 = s1[-1] + s1[:-1]
   rotations = 1

   while rotations <= n:
      if s1 == s2:
         return rotations
      s1 = s1[-1] + s1[:-1]
      rotations += 1

   return -1
# Example usage
s1 = "program"
s2 = "grampro"
efficient_result = min_rotations_efficient(s1, s2)

print("String 1:", s1)
print("String 2:", s2)
print("Minimum rotations ", efficient_result)

Output

String 1: program
String 2: grampro
Minimum rotations  3

Conclusion

In this article, we looked at two methods for calculating the bare minimum of rotations needed to transform a given string into another string. While the second approach uses a concatenated string to check for the presence of the second string, the brute force approach rotates the first string by every feasible number of positions. One can choose the best strategy to tackle this problem in Python depending on the size of the input and the needed efficiency. You now can calculate the lowest number of rotations necessary to extract a target string from a given string thanks to your grasp of these methods.

Updated on: 28-Jul-2023

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements