0

Is there any faster( beside going through the whole loop O(n)) way to find the no of duplicates of a number from a sorted list.

searching

20th Oct 2018, 6:51 AM
Kunal Kumar Thakur
Kunal Kumar Thakur - avatar
5 Antworten
+ 3
I don't know if it will be faster but you don't have to go trough the whole list (it is an example in python): l = [1, 2, 3, 3, 3, 4, 4, 5] total = 0 z = 4 try: for i in range (l.index(z), len(l) ): if l[i] == z: total += 1 if l[i] > z: break except: pass print (total)
20th Oct 2018, 7:39 AM
Paul
Paul - avatar
+ 2
If the list is sorted, you can easily find both the first and the last positions of a given number (O(logn)). Everything in between also is duplicate, no additional check is needed.
20th Oct 2018, 7:58 AM
Микола Федосєєв
Микола Федосєєв - avatar
+ 2
you mean to say i would apply binary search twice to get the first and last position and just subtract it to get the count. Thanks didn't clicked to me.
20th Oct 2018, 8:07 AM
Kunal Kumar Thakur
Kunal Kumar Thakur - avatar
+ 2
In python you could use the Counter module. I can't guarantee that it is faster than O(n) but usually using the most specific module is said to give better and more efficient results than anything you create yourself. from collections import Counter a = [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4] n = 2 print(Counter(a)[n]) #output: 17
20th Oct 2018, 9:12 AM
Anna
Anna - avatar
0
The Counter module seems to be O(n), as it handles all array values during initialization.
20th Oct 2018, 5:30 PM
Микола Федосєєв
Микола Федосєєв - avatar