Count of common subarrays in two different permutations of 1 to N | Javascript implementation of the above approach ; Initialising Map for Index Mapping ; Mapping elements of A ; Modify elements of B according to Map ; Changing B [ i ] as the index of B [ i ] in A ; Count of common subarrays ; Traversing array B ; While consecutive elements are found , we increment K ; Add number of subarrays with length K to total count ; Driver Code
function commonSubarrays ( A , B , N ) { let Map = Array . from ( { length : N + 1 } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < N ; i ++ ) Map [ A [ i ] ] = i ; for ( let i = 0 ; i < N ; i ++ ) { B [ i ] = Map [ B [ i ] ] ; } let count = 0 ; let i = 0 , K ; while ( i < N ) { K = 1 ; i += 1 ; while ( i < N && B [ i ] == B [ i - 1 ] + 1 ) { i += 1 ; K += 1 ; } count = count + ( ( K ) * ( K + 1 ) ) / 2 ; } return count ; } let N = 3 ; let A = [ 1 , 2 , 3 ] ; let B = [ 2 , 3 , 1 ] ; document . write ( commonSubarrays ( A , B , N ) ) ; document . write ( " " ) ; N = 5 ; let C = [ 1 , 2 , 3 , 4 , 5 ] ; let D = [ 2 , 3 , 1 , 4 , 5 ] ; document . write ( commonSubarrays ( C , D , N ) ) ;