Check if a string can be obtained by rotating another string d places | Function to reverse an array from left index to right index ( both inclusive ) ; Function that returns true if str1 can be made equal to str2 by rotating either d places to the left or to the right ; Left Rotation string will contain the string rotated Anti - Clockwise Right Rotation string will contain the string rotated Clockwise ; Copying the str1 string to left rotation string and right rotation string ; Rotating the string d positions to the left ; Rotating the string d positions to the right ; Compairing the rotated strings ; If cannot be made equal with left rotation ; If cannot be made equal with right rotation ; If both or any one of the rotations of str1 were equal to str2 ; Driver code ; d is the rotating factor ; In case length of str1 < d
def ReverseArray ( arr , left , right ) : NEW_LINE INDENT while ( left < right ) : NEW_LINE INDENT temp = arr [ left ] ; NEW_LINE arr [ left ] = arr [ right ] ; NEW_LINE arr [ right ] = temp ; NEW_LINE left += 1 ; NEW_LINE right -= 1 ; NEW_LINE DEDENT DEDENT def RotateAndCheck ( str1 , str2 , d ) : NEW_LINE INDENT if ( len ( str1 ) != len ( str2 ) ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT left_rot_str1 = [ ] ; right_rot_str1 = [ ] ; NEW_LINE left_flag = True ; right_flag = True ; NEW_LINE str1_size = len ( str1 ) ; NEW_LINE for i in range ( str1_size ) : NEW_LINE INDENT left_rot_str1 . append ( str1 [ i ] ) ; NEW_LINE right_rot_str1 . append ( str1 [ i ] ) ; NEW_LINE DEDENT ReverseArray ( left_rot_str1 , 0 , d - 1 ) ; NEW_LINE ReverseArray ( left_rot_str1 , d , str1_size - 1 ) ; NEW_LINE ReverseArray ( left_rot_str1 , 0 , str1_size - 1 ) ; NEW_LINE ReverseArray ( right_rot_str1 , 0 , str1_size - d - 1 ) ; NEW_LINE ReverseArray ( right_rot_str1 , str1_size - d , str1_size - 1 ) ; NEW_LINE ReverseArray ( right_rot_str1 , 0 , str1_size - 1 ) ; NEW_LINE for i in range ( str1_size ) : NEW_LINE INDENT if ( left_rot_str1 [ i ] != str2 [ i ] ) : NEW_LINE INDENT left_flag = False ; NEW_LINE DEDENT if ( right_rot_str1 [ i ] != str2 [ i ] ) : NEW_LINE INDENT right_flag = False ; NEW_LINE DEDENT DEDENT if ( left_flag or right_flag ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = list ( " abcdefg " ) ; NEW_LINE str2 = list ( " cdefgab " ) ; NEW_LINE d = 2 ; NEW_LINE d = d % len ( str1 ) ; NEW_LINE if ( RotateAndCheck ( str1 , str2 , d ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT