Find the number of sub arrays in the permutation of first N natural numbers such that their median is M | Function to return the count of sub - arrays in the given permutation of first n natural numbers such that their median is m ; If element is less than m ; If element greater than m ; If m is found ; Count the answer ; Increment Sum ; Driver code
def segments ( n , p , m ) : NEW_LINE INDENT c = dict ( ) NEW_LINE c [ 0 ] = 1 NEW_LINE has = False NEW_LINE Sum = 0 NEW_LINE ans = 0 NEW_LINE for r in range ( n ) : NEW_LINE INDENT if ( p [ r ] < m ) : NEW_LINE INDENT Sum -= 1 NEW_LINE DEDENT elif ( p [ r ] > m ) : NEW_LINE INDENT Sum += 1 NEW_LINE DEDENT if ( p [ r ] == m ) : NEW_LINE INDENT has = True NEW_LINE DEDENT if ( has ) : NEW_LINE INDENT if ( Sum in c . keys ( ) ) : NEW_LINE INDENT ans += c [ Sum ] NEW_LINE DEDENT if Sum - 1 in c . keys ( ) : NEW_LINE INDENT ans += c [ Sum - 1 ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT c [ Sum ] = c . get ( Sum , 0 ) + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 2 , 4 , 5 , 3 , 1 ] NEW_LINE n = len ( a ) NEW_LINE m = 4 NEW_LINE print ( segments ( n , a , m ) ) NEW_LINE