imashutosh51

Number of occurrence of x in array

Jul 31st, 2022 (edited)
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. def left_index(l,r,arr,target):
  2.     if l>r:
  3.         return -1
  4.     mid= (l+r)//2
  5.     if arr[mid]==target and (mid==0 or arr[mid-1]!=target):
  6.         return mid
  7.     elif arr[mid]>=target:
  8.         return left_index(l,mid-1,arr,target)
  9.     else:
  10.         return left_index(mid+1,r,arr,target)
  11.  
  12. def right_index(l,r,arr,target):
  13.     if l>r:
  14.         return -1
  15.     mid=(l+r)//2
  16.     if arr[mid]==target and (mid==len(arr)-1 or arr[mid+1]!=target):
  17.         return mid
  18.     elif arr[mid]>target:
  19.         return right_index(l,mid-1,arr,target)
  20.     else:
  21.         return right_index(mid+1,r,arr,target)
  22.        
  23. class Solution:
  24.     def countFreq(self, arr, target):
  25.         first=left_index(0,len(arr)-1,arr,target)
  26.         last=right_index(0,len(arr)-1,arr,target)
  27.         return last-first+1 if first!=-1 else 0
  28.        
  29. #M-2 Using prebuild functions
  30.  
  31. from bisect import bisect_left,bisect_right      
  32. class Solution:
  33.     def countFreq(self, arr, target):
  34.         first=bisect_left(arr,target)
  35.         last=bisect_right(arr,target) #it gives the next element index after the target
  36.         return last-first if first<len(arr) and arr[first]==target else 0
  37.        
  38.        
Advertisement
Add Comment
Please, Sign In to add comment