Count of common subarrays in two different permutations of 1 to N | C # 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
using System ; class GFG { static int commonSubarrays ( int [ ] A , int [ ] B , int N ) { int [ ] Map = new int [ N + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) Map [ A [ i ] ] = i ; for ( int i = 0 ; i < N ; i ++ ) { B [ i ] = Map [ B [ i ] ] ; } int count = 0 ; int a = 0 , K ; while ( a < N ) { K = 1 ; a += 1 ; while ( a < N && B [ a ] == B [ a - 1 ] + 1 ) { a += 1 ; K += 1 ; } count = count + ( ( K ) * ( K + 1 ) ) / 2 ; } return count ; } public static void Main ( ) { int N = 3 ; int [ ] A = { 1 , 2 , 3 } ; int [ ] B = { 2 , 3 , 1 } ; Console . Write ( commonSubarrays ( A , B , N ) ) ; Console . Write ( " STRNEWLINE " ) ; N = 5 ; int [ ] C = { 1 , 2 , 3 , 4 , 5 } ; int [ ] D = { 2 , 3 , 1 , 4 , 5 } ; Console . Write ( commonSubarrays ( C , D , N ) ) ; } }