Rotate String in Python

Suppose we have two strings, A and B. We will rotate the string A and check whether it matches with B at any position of rotating, if so then return true, otherwise false. For example, if A = 'abcde', and B = 'bcdea' So answer will be true, as A can be converted to B after rotating it.

To solve this, we will follow these steps −

  • When both A and B are empty, then return true, when both are of different length then return false
  • A := concatenate A after A
  • i := 0, and j := 0
  • while i < length of A
    • if length of A – i + 1 < length of B, then return false
    • while i < length of A and j < length of B and A[i] = B[j]
      • increase i and j by 1
    • if j = length of B then returns true
    • if j is not 0, then decrease i by 1
    • j := 0
    • increase i by 1


Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def rotateString(self, A, B):
      if not A and not B:
         return True
      if len(A) != len(B):
         return False
      A = A*2
      i = 0
      while i < len(A):
         if len(A)-i+1<len(B):
            return False
         while i<len(A) and j < len(B) and A[i] == B[j]:
         if j == len(B):
            return True
         if j:
ob1 = Solution()
print(ob1.rotateString("abcde", "cdeab"))





Updated on: 28-Apr-2020


Kickstart Your Career

Get certified by completing the course

Get Started