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
function ReverseArray ( arr , left , right ) { var temp ; while ( left < right ) { temp = arr [ left ] ; arr [ left ] = arr [ right ] ; arr [ right ] = temp ; left ++ ; right -- ; } } function RotateAndCheck ( str1 , str2 , d ) { if ( str1 . length !== str2 . length ) return false ; var left_rot_str1 = [ ] ; var right_rot_str1 = [ ] ; var left_flag = true , right_flag = true ; var str1_size = str1 . length ; for ( var i = 0 ; i < str1_size ; i ++ ) { left_rot_str1 . push ( str1 [ i ] ) ; right_rot_str1 . push ( str1 [ i ] ) ; } ReverseArray ( left_rot_str1 , 0 , d - 1 ) ; ReverseArray ( left_rot_str1 , d , str1_size - 1 ) ; ReverseArray ( left_rot_str1 , 0 , str1_size - 1 ) ; ReverseArray ( right_rot_str1 , 0 , str1_size - d - 1 ) ; ReverseArray ( right_rot_str1 , str1_size - d , str1_size - 1 ) ; ReverseArray ( right_rot_str1 , 0 , str1_size - 1 ) ; for ( var i = 0 ; i < str1_size ; i ++ ) { if ( left_rot_str1 [ i ] !== str2 [ i ] ) { left_flag = false ; } if ( right_rot_str1 [ i ] !== str2 [ i ] ) { right_flag = false ; } } if ( left_flag right_flag ) return true ; return false ; } var str1 = " " ; var str2 = " " ; var d = 2 ; d = d % str1 . length ; if ( RotateAndCheck ( str1 , str2 , d ) ) document . write ( " " ) ; else document . write ( " " ) ;