Showing posts with label Duplicate. Show all posts
Showing posts with label Duplicate. Show all posts

Friday 6 July 2012

Find duplicates in O(n) time and O(1) extra space


Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times.Find these repeating numbers in O(n) and using only constant memory space.

For example, let n be 7 and array be {1, 2, 3, 1, 3, 0, 6}, the answer should be 1 & 3.



#include<stdio.h>
#include<math.h>
int main()
{
    int n,A[15],i,flage,cycle=0,j,temp;
    printf("\nEnter size of array : ");
    scanf("%d",&n);
    printf("\nEnter elements of array( %d space saperated  integer) : \n",n );
    for(i=0;i<n;i++)
      scanf("%d",&A[i]);
    flage=0;j=0;
    printf("\n OUTPUT : ");

    for(i=0;i<n;i++)
    {
        if( A[abs(A[i])] >= 0)
           A[abs(A[i])]=-A[abs(A[i])];
        else
            printf(" %d",abs(A[i]) );
    }
return 0;
}

Let me know your thoughts.