human
Write me a code to count of common subarrays in two different permutations of 1 to N and the other steps required given the following:
Count of common subarrays in two different permutations of 1 to N | Python3 implementation of 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"
How can the above be solved in Python?
assistant
#Here is code to count of common subarrays in two different permutations of 1 to N and the other steps required.
 def commonSubarrays ( A , B , N ) :
	Map = [ 0 for i in range ( N + 1 ) ]
	for i in range ( N ) :
		Map [ A [ i ] ] = i
	for i in range ( N ) :
		B [ i ] = Map [ B [ i ] ]
	count = 0
	i = 0
	while i < N :
		K = 1
		i += 1
		while i < N and B [ i ] == B [ i - 1 ] + 1 :
			i += 1
			K += 1
		count = count + ( ( K ) * ( K + 1 ) ) // 2
	return count
N = 3
A = [ 1 , 2 , 3 ]
B = [ 2 , 3 , 1 ]
print ( commonSubarrays ( A , B , N ) )
N = 5
A = [ 1 , 2 , 3 , 4 , 5 ]
B = [ 2 , 3 , 1 , 4 , 5 ]
print ( commonSubarrays ( A , B , N ) )