Open In App

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

Last Updated : 09 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings s1 and s2. The task is to find out the minimum number of string rotations for the given string s1 to obtain the actual string s2. Examples:

Input : eeksg, geeks
Output: 1 
Explanation: g is rotated left to obtain geeks.

Input : eksge, geeks
Output: 2
Explanation : e and g are left rotated to obtain geeks.

Approach:

  • Use string slicing to rotate the string.
  • Perform right rotations str1=str1[1:len(str1)]+str1[0] on string to obtain the actual string.
  • Perform left rotations m=m[len(m)-1]+m[:len(m)-1] on string to obtain the actual string.
  • Print the minimum of left(x) and right(y) rotations.

TIME COMPLEXITY: O(n) Below is the implementation: 

python3




def findRotations(str1, str2):
     
    # To count left rotations
    # of string
    x = 0
     
    # To count right rotations
    # of string
    y = 0
    m = str1
     
    while True:
         
        # left rotating the string
        m = m[len(m)-1] + m[:len(m)-1]
         
        # checking if rotated and
        # actual string are equal.
        if(m == str2):
            x += 1
            break
             
        else:
            x += 1
            if x > len(str2) :
                break
  
    while True:
         
        # right rotating the string
        str1 = str1[1:len(str1)]+str1[0]
         
        # checking if rotated and actual
        # string are equal.
        if(str1 == str2):
            y += 1
            break
             
        else:
            y += 1
            if y > len(str2):
                break
                 
    if x < len(str2):
         
        # printing the minimum
        # number of rotations.
        print(min(x,y))
         
    else:
        print("given strings are not of same kind")
         
# Driver code
findRotations('sgeek', 'geeks')


Output:

1

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)

Auxiliary Space: O(n)



Similar Reads

Python - Actual order index distance
Sometimes we have an unsorted list and we wish to find the actual position the elements could be when they would be sorted, i.e we wish to construct the list which could give the position distance to each element destined if the list was sorted. This has a good application in web development and competitive programming domain. Let’s discuss certain
3 min read
Python3 Program for Minimum rotations required to get the same string
Given a string, we need to find the minimum number of rotations required to get the same string.Examples: Input : s = "geeks" Output : 5 Input : s = "aaaa" Output : 1 Method 1: The idea is based on below post.A Program to check if strings are rotations of each other or notStep 1 : Initialize result = 0 (Here result is count of rotations)Step 2 : Ta
2 min read
Python3 Program for Find element at given index after a number of rotations
An array consisting of N integers is given. There are several Right Circular Rotations of range[L..R] that we perform. After performing these rotations, we need to find element at a given index.Examples : Input : arr[] : {1, 2, 3, 4, 5} ranges[] = { {0, 2}, {0, 3} } index : 1Output : 3Explanation : After first given rotation {0, 2} arr[] = {3, 1, 2
6 min read
Python3 Program to Check whether all the rotations of a given number is greater than or equal to the given number or not
Given an integer x, the task is to find if every k-cycle shift on the element produces a number greater than or equal to the same element. A k-cyclic shift of an integer x is a function that removes the last k digits of x and inserts them in its beginning. For example, the k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2. Print Yes if the giv
3 min read
How to obtain the line number in which given word is present using Python?
To obtain the line number from the file where the given word is present, create a list in which each index contains the content of each line with Python. To do so follow the below instruction. Get Line Number of Certain Phrase in a Text fileBelow are the methods that we will cover in this article. Using IterationUsing EnumerateInput file: File1.txt
3 min read
Python Program to Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
Given an array, only rotation operation is allowed on array. We can rotate the array as many times as we want. Return the maximum possible summation of i*arr[i]. Examples :   Input: arr[] = {1, 20, 2, 10} Output: 72 We can get 72 by rotating array twice. {2, 10, 1, 20} 20*3 + 1*2 + 10*1 + 2*0 = 72 Input: arr[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9} Outp
3 min read
Python Program to Find the Maximum sum of i*arr[i] among all rotations of a given array
Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1. Examples: Input: arr[] = {8, 3, 1, 2} Output: 29 Explanation: Lets look at all the rotations, {8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11 {3, 1, 2, 8} = 3*0 + 1*1 + 2*2 + 8*3 = 29 {1, 2, 8, 3} = 1*0 + 2*1 + 8*2 + 3*3 = 27
6 min read
Python3 Program to Find Mth element after K Right Rotations of an Array
C/C++ Code # Python3 program to implement # the above approach # Function to return Mth element of # array after k right rotations def getFirstElement(a, N, K, M): # The array comes to original state # after N rotations K %= N # If K is greater or equal to M if (K &gt;= M): # Mth element after k right # rotations is (N-K)+(M-1) th # element of the
1 min read
Python3 Program to Find the Mth element of the Array after K left rotations
Given non-negative integers K, M, and an array arr[] with N elements find the Mth element of the array after K left rotations. Examples: Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1Output: 5Explanation: The array after first left rotation a1[ ] = {4, 5, 23, 3}The array after second left rotation a2[ ] = {5, 23, 3, 4}1st element after 2 left rotations
2 min read
Python3 Program to Find Range sum queries for anticlockwise rotations of Array by K indices
Given an array arr consisting of N elements and Q queries of the following two types: 1 K: For this type of query, the array needs to be rotated by K indices anticlockwise from its current state.2 L R: For this query, the sum of the array elements present in the indices [L, R] needs to be calculated. Example: Input: arr = { 1, 2, 3, 4, 5, 6 }, quer
4 min read
Practice Tags :
three90RightbarBannerImg