Search code examples
pythonarrayspython-3.xoptimizationmedian

Getting timeout error for some cases in python 3.x


I am working on the Fraudulent Activity Notification problem: https://www.hackerrank.com/challenges/fraudulent-activity-notifications/. And I have written the below code to solve this problem. This code runs fine for some of the test cases but fails for some of them, giving time out error. Can anyone help me in understanding how can i optimize it and make it better?

def calculate_median(lists):    
    n = len(lists)
    lists.sort()
    if n % 2 == 0: 
        median1 = lists[n//2] 
        median2 = lists[n//2 - 1] 
        median = (median1 + median2)/2
    else: 
        median = lists[n//2] 
    return median


my_list = [2,3,4,2,3,6,8,4,5]
d=5
n = len(my_list)
count = 0
start= 0
end = d
for i in range(0, len(my_list)):
    if end < n:
        seg_list = my_list[start:end]
        check_val = my_list[end]
        median_val = calculate_median(seg_list)
        if check_val >= 2 *median_val:
            count = count +1 
        start = start + 1
        end = end + 1

print(count)

Solution

  • I have used bisect_left and insort_left to solve this problem. This is one of the optimized way to do it.

    from bisect import bisect_left, insort_left
    count = 0
    listD = sorted(my_list[:d])
    
    def median():
       return listD[d//2] if d%2 == 1 else ((listD[d//2] + listD[d//2-1])/2)
    
    for i in range(d,n):
       if my_list[i] >= 2*median(): 
          count += 1
       del listD[bisect_left(listD, my_list[i-d])]
       insort_left(listD, my_list[i])
    print(count)