Suppose we have an array A containing the permutation of first N natural numbers and another number M is also given, where M ≤ N, we have to find the number of sub-arrays such that the median of the sequence is M. As we know the median of a sequence is defined as the value of the element which is in the middle of the sequence after sorting it according to ascending order. For even length sequence, the left of two middle elements is used.
So, if the input is like A = [3, 5, 6, 4, 2] and M = 5, then the output will be 4 as the required subarrays are [3, 5, 6], [5], [5, 6] and [5, 6, 4].
To solve this, we will follow these steps −
n := size of arr
my_map := a new map
my_map[0] := 1
has := False, add := 0, result := 0
for i in range 0 to n, do
if arr[i] < m, then
add := add - 1
otherwise when arr[i] > m, then
add := add + 1
if arr[i] is same as m, then
has := True
if has is true, then
if add present in my_map, then
result := result + my_map[add]
if add-1 present in my_map , then
result := result + my_map[add - 1]
otherwise,
my_map[add] := (value of my_map[add], if present, otherwise 0) + 1
return result
Example
Let us see the following implementation to get better understanding −
def solve(arr, m): n = len(arr) my_map = {} my_map[0] = 1 has = False add = 0 result = 0 for i in range(n): if (arr[i] < m): add -= 1 elif (arr[i] > m): add += 1 if (arr[i] == m): has = True if (has): if(add in my_map): result += my_map[add] if add-1 in my_map: result += my_map[add - 1] else: my_map[add] = my_map.get(add, 0) + 1 return result arr = [3, 5, 6, 4, 2] m = 5 print(solve(arr, m))
Input
[3, 5, 6, 4, 2] , 5
Output
3