We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The reason why Python times out despite being O(n log n) is because of the pop(0) operation, which is actually O(n) time, which is nested within the merge() O(n) operation. Why is pop(0) O(n)?
The solution is to transform the list into a deque in O(n) time once, and then all pop(0) operations are now O(1).
fromcollectionsimportdequedefcountInversions(arr):# Write your code hereglobalansans=0defmergesort(x):n=len(x)iflen(x)==1:returnxelse:returnmerge(mergesort(x[:n//2]), mergesort(x[n//2:]))defmerge(a,b):# print(a, b) res=[]a=deque(a)b=deque(b)whileaandb:x=a[0]y=b[0]ify<x:globalansans+=len(a)res.append(y)b.popleft()else:res.append(x)a.popleft()ifa:res.extend(a)ifb:res.extend(b)returnresmergesort(arr)returnans
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Merge Sort: Counting Inversions
You are viewing a single comment's thread. Return to all comments →
The reason why Python times out despite being O(n log n) is because of the pop(0) operation, which is actually O(n) time, which is nested within the merge() O(n) operation. Why is pop(0) O(n)?
The solution is to transform the list into a deque in O(n) time once, and then all pop(0) operations are now O(1).