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:

  • Using Brute Force Method

  • Using String Concatenation Method

Let us investigate both approaches in detail.

Method 1: Using Brute Force

The brute force method rotates the first string by all possible positions and compares each rotation with the target string. We maintain track of the minimal number of rotations necessary to obtain the target string by iterating over all possible rotations. The time complexity of this method is O(n²), where n is the length of the string.

Algorithm

The steps to find minimum number of rotations using brute force are:

Step 1 ? Create a function with two strings as input parameters

Step 2 ? Initialize a variable to track the minimum number of rotations

Step 3 ? Iterate from 0 to the length of the first string

Step 4 ? Rotate the first string by current index positions and compare with target

Step 5 ? Update minimum rotations if match is found

Step 6 ? Return minimum rotations or -1 if no match found

Example

def min_rotations_bf(s1, s2):
    if len(s1) != len(s2):
        return -1
    
    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)

The output of the above code is:

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

Method 2: Using String Concatenation

The efficient method uses string concatenation to check if the target string exists as a substring. By concatenating the source string with itself, all possible rotations become substrings of this concatenated string. The time complexity of this method is O(n), where n is the length of the string.

Algorithm

The steps to find minimum rotations using string concatenation are:

Step 1 ? Create a function with two strings as input

Step 2 ? Check if both strings have equal length

Step 3 ? Concatenate the first string with itself

Step 4 ? Find the index of target string in concatenated string

Step 5 ? Return the index as minimum rotations or -1 if not found

Example

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

    # Concatenate s1 with itself
    concatenated = s1 + s1
    
    # Check if s2 is a substring of concatenated string
    if s2 in concatenated:
        return concatenated.find(s2)
    else:
        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):", efficient_result)

The output of the above code is:

String 1: program
String 2: grampro
Minimum rotations (Efficient): 3

Comparison of Methods

Method Time Complexity Space Complexity Best For
Brute Force O(n²) O(n) Educational purposes
String Concatenation O(n) O(n) Production code

Complete Example

def min_rotations_bf(s1, s2):
    if len(s1) != len(s2):
        return -1
    
    min_rotations = float('inf')
    for i in range(len(s1)):
        rotated = s1[i:] + s1[:i]
        if rotated == s2:
            min_rotations = min(min_rotations, i)
    
    return min_rotations if min_rotations != float('inf') else -1

def min_rotations_efficient(s1, s2):
    if len(s1) != len(s2):
        return -1
    
    concatenated = s1 + s1
    return concatenated.find(s2) if s2 in concatenated else -1

# Test both methods
test_cases = [("program", "grampro"), ("abcde", "cdeab"), ("hello", "world")]

for s1, s2 in test_cases:
    bf_result = min_rotations_bf(s1, s2)
    eff_result = min_rotations_efficient(s1, s2)
    print(f"'{s1}' ? '{s2}': BF={bf_result}, Efficient={eff_result}")

The output of the above code is:

'program' ? 'grampro': BF=3, Efficient=3
'abcde' ? 'cdeab': BF=2, Efficient=2
'hello' ? 'world': BF=-1, Efficient=-1

Conclusion

We explored two methods for finding the minimum rotations needed to transform one string into another. The brute force approach has O(n²) complexity while the string concatenation method achieves O(n) complexity. Use the efficient concatenation method for better performance in production code.

Updated on: 2026-03-27T10:31:27+05:30

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements