Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of appearances of a value in a sorted array in O(log n) complexity

How can I build a function that returns the number of appearances of a given int x in a sorted array, in O(log n) complexity?

static public int count (int [] a, int x);

I'm thinking I might use a binary search to the find the first / last appearance, then continue searching for the last / first appearance, and return the number of instances, but that this is O(log n) complexity .

like image 540
Zvi vex Avatar asked Dec 22 '25 02:12

Zvi vex


1 Answers

Your idea actually works in time O(log n) if you implement it correctly. Do one binary search to find the index i of the first copy of the element, then do another binary search to find the index j of the last copy of the element, then return j - i + 1. Each binary search takes time O(log n), so the total work done is O(log n) + O(log n) = O(log n).

like image 71
templatetypedef Avatar answered Dec 23 '25 16:12

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!