Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def left_index(l,r,arr,target):
- if l>r:
- return -1
- mid= (l+r)//2
- if arr[mid]==target and (mid==0 or arr[mid-1]!=target):
- return mid
- elif arr[mid]>=target:
- return left_index(l,mid-1,arr,target)
- else:
- return left_index(mid+1,r,arr,target)
- def right_index(l,r,arr,target):
- if l>r:
- return -1
- mid=(l+r)//2
- if arr[mid]==target and (mid==len(arr)-1 or arr[mid+1]!=target):
- return mid
- elif arr[mid]>target:
- return right_index(l,mid-1,arr,target)
- else:
- return right_index(mid+1,r,arr,target)
- class Solution:
- def countFreq(self, arr, target):
- first=left_index(0,len(arr)-1,arr,target)
- last=right_index(0,len(arr)-1,arr,target)
- return last-first+1 if first!=-1 else 0
- #M-2 Using prebuild functions
- from bisect import bisect_left,bisect_right
- class Solution:
- def countFreq(self, arr, target):
- first=bisect_left(arr,target)
- last=bisect_right(arr,target) #it gives the next element index after the target
- return last-first if first<len(arr) and arr[first]==target else 0
Advertisement
Add Comment
Please, Sign In to add comment