Count number of common elements between a sorted array and a reverse sorted array | Function to count the number of elements common in both the arrays ; Used to traverse array A [ ] and B [ ] from the front and the back ; Stores the count of numbers common in both array ; If A [ first ] is less than B [ second ] ; Increment the value of first ; IF B [ second ] is less than A [ first ] ; Decrement the value of second ; A [ first ] is equal to B [ second ] ; Increment the value of count ; Increment the value of first ; Decrement the value of second ; Return the value of count ; Driver Code
def countEqual ( A , B , N ) : NEW_LINE INDENT first = 0 NEW_LINE second = N - 1 NEW_LINE count = 0 NEW_LINE while ( first < N and second >= 0 ) : NEW_LINE INDENT if ( A [ first ] < B [ second ] ) : NEW_LINE INDENT first += 1 NEW_LINE DEDENT elif ( B [ second ] < A [ first ] ) : NEW_LINE INDENT second -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE first += 1 NEW_LINE second -= 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT A = [ 2 , 4 , 5 , 8 , 12 , 13 , 17 , 18 , 20 , 22 , 309 , 999 ] NEW_LINE B = [ 109 , 99 , 68 , 54 , 22 , 19 , 17 , 13 , 11 , 5 , 3 , 1 ] NEW_LINE N = len ( A ) NEW_LINE print ( countEqual ( A , B , N ) ) NEW_LINE