Solution #1: We will use the modified binary search to solve this in O(log n) time. Here is the code,
int count(int* arr, int x, int start, int end) { if(start > end) return; int mid = (start+end)/2; int cnt = 0; if(arr[mid] == x) cnt = 1 + count(arr, x, start, mid-1) + count(arr, x, mid+1, end); else if(arr[mid] > x) cnt = count(arr, x, start, mid-1); else cnt = count(arr, x, mid+1, end); return cnt; }
5 comments:
The time complex of the algorithm you are giving is not o(lgn);
it is o(n). T(n) = T(n/2)+T(n/2)+1 is O(n).
1. It is fact that when u are recursing in both side of the array then u will have O(n) time.
2. What if the duplicate element is not known beforehand. As you have assumed occurence of x ut actually if that key is not known to us .. Just asked you to find the existence of duplicate element
Nice post.
Keep up the good job.
How can we find the first index and the last index of the given element?
We can find out the duplicate element by using Set, list or trvaersing using loop on array.
Below link can be useful to find out the algorithm to find duplicate or repeated elements in an array in java
Find out duplicate or repeated elements in an array in java
Post a Comment