Check if strings are rotations of each other or not | Set 2 | javascript program to check if two strings are rotations of each other . ; create lps that will hold the longest prefix suffix values for pattern ; length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; the loop calculates lps [ i ] for i = 1 to n - 1 ; match from that rotating point ; Driver code
function isRotation ( a , b ) { var n = a . length ; var m = b . length ; if ( n != m ) return false ; var lps = Array . from ( { length : n } , ( _ , i ) => 0 ) ; var len = 0 ; var i = 1 ; lps [ 0 ] = 0 ; while ( i < n ) { if ( a . charAt ( i ) == b . charAt ( len ) ) { lps [ i ] = ++ len ; ++ i ; } else { if ( len == 0 ) { lps [ i ] = 0 ; ++ i ; } else { len = lps [ len - 1 ] ; } } } i = 0 ; for ( k = lps [ n - 1 ] ; k < m ; ++ k ) { if ( b . charAt ( k ) != a . charAt ( i ++ ) ) return false ; } return true ; } var s1 = " " ; var s2 = " " ; document . write ( isRotation ( s1 , s2 ) ? " " : " " ) ;