Web Toolbar by Wibiya

Pages

Wednesday, January 25, 2012

Given a sorted array with duplicate elements, find the number of occurrences of x.

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:

Anonymous said...

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).

creative@avijit.prog.com said...

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

Leonis said...

Nice post.
Keep up the good job.

gokhaled89 said...

How can we find the first index and the last index of the given element?

Aashish said...

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