Advertisement
Iam_Sandeep

315. Count of Smaller Numbers After Self

Jul 11th, 2022 (edited)
875
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. class Solution:
  2.     def countSmaller(self, nums: List[int]) -> List[int]:
  3.         def merge(a):
  4.             if not a or len(a)==1:return
  5.             n=len(a)
  6.             m=n//2
  7.             L,R=a[:m],a[m:]
  8.             merge(L)
  9.             merge(R)
  10.             i,j,k,m,n=0,0,0,len(L),len(R)
  11.             count=0
  12.             while i<m and j<n:
  13.                 #print(L,R,i,j,k)
  14.                 if L[i][0]>R[j][0]:
  15.                     a[k]=R[j]
  16.                     count+=1    #we add all small numbers that are less than value at L[i] because they are inversions. We add the count of L[i] at once while we are adding L[i] to merged array
  17.                     j,k=j+1,k+1
  18.                 else:
  19.                     _,idx=L[i]
  20.                     a[k]=L[i]#so here we are adding L[i]. So we should update the count so far happened and we wont make this 0 because since array is sorted we will be using the same count for upcoming values
  21.                     ans[idx]+=count
  22.                     i,k=i+1,k+1
  23.             while i<m:
  24.                 _,idx=L[i]
  25.                 a[k]=L[i]
  26.                 ans[idx]+=count#So far only left section elements are left. So we just fill previous count for this. Because if the count denotes no of smaller points to right side of that previous value then obviou same count will be used for current value since it is sorted
  27.                 i,k=i+1,k+1
  28.             while j<n:
  29.                 a[k]=R[j]
  30.                 count+=1# You can just avoid.Because these are remained empty right section numbers
  31.                 j,k=j+1,k+1
  32.             #print(L,R,ans,a)
  33.         '''
  34.         Why are we adding tuple (j,i) . Because when we slice we loos indexes while doing merge sort.
  35.         '''
  36.         a=[(j,i) for i,j in enumerate(nums)]
  37.         ans=[0]*len(nums)
  38.         merge(a)
  39.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement