imashutosh51

Count inversions

Aug 10th, 2022 (edited)
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. '''
  2.  
  3. Brute Force; Two loops- i(0:n-2) & j(i+1:n-1) if arr[j] element is smaller than arr[i], increment the ans.No need to swap. Time complexity O(N^2)
  4.  
  5. T.C O(nlogn) S.C O(n)
  6. logic:
  7. *We want pair of elements where first element should be greater and second should be smaller.
  8. *We applied merge sort but while merging two sorted arrays,if left array ie. arr1 ith
  9. element which is greater than jth element of right array ie. arr2 then all the elements
  10. after ith element including ith element will be greater than jth element of arr2 because
  11. both array is sorted so that satisfies our condition so we will add that in answer.
  12.  
  13. ###None of the merge sort function returns any array or anything else.
  14. '''
  15.  
  16. def merge(arr,l,mid,r,ans):
  17.     final_arr=[]
  18.     i,j=l,mid+1
  19.    
  20.     '''
  21.    First thing you should understand both left and right table will be sorted in ascending order for sure at this step.
  22.    so for eg. left arr=[2,5,8,12] and right_arr=[3,6,9] so after pushing 2 into the final array, when 3 comes which is smaller than [5,8,12] so
  23.    our answer should increase by (mid-i+1) where i points ot 5 so mid-i+1 is all the remaining elments of the left array because if kth elmenet is bigger than
  24.    3(from right array of our example) then all the elments of the left array will be bigger only as both array are sorted.
  25.    '''
  26.     while i<=mid and j<=r:
  27.         if arr[i]<=arr[j]:
  28.             final_arr.append(arr[i])
  29.             i+=1
  30.         else:
  31.             '''Here jth element which is greater than all the elmenets of '''
  32.             final_arr.append(arr[j])
  33.             ans[0]+=(mid-i+1)
  34.             j+=1
  35.     if j>r:
  36.         while i<=mid:
  37.             final_arr.append(arr[i])
  38.             i+=1
  39.     elif i>mid:
  40.         while j<=r:
  41.             final_arr.append(arr[j])
  42.             ans[0]+=(mid-i+1)
  43.             j+=1
  44.     arr[l:r+1] = final_arr
  45.    
  46.  
  47.  
  48. def mergesort(arr,i,j,ans):
  49.     if i<j:
  50.         mid= (i+j)//2
  51.         mergesort(arr,i,mid,ans)
  52.         mergesort(arr,mid+1,j,ans)
  53.         merge(arr,i,mid,j,ans)
  54.  
  55. class Solution:
  56.     def inversionCount(self, arr):
  57.         ans=[0]
  58.         mergesort(arr,0,len(arr)-1,ans)
  59.         return ans[0]
Advertisement
Add Comment
Please, Sign In to add comment