VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-to-find-minimum-number-of-rotations-to-obtain-actual-string/

⇱ Python Program to find minimum number of rotations to obtain actual string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 9 Sep, 2022

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: 

Output:
1

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

Time Complexity: O(n)

Auxiliary Space: O(n)

Comment