CapitalIQ Interview Question
ConsultantsCountry: India
Interview Type: Phone Interview
Questions you ought to ask for clarification:
1.) Is the array sorted?
2.) Does the array order need to be maintained?
A.) If it's sorted, you can do it in O(n) with no additional data structures.
B.) If the order does not need to be maintained, then I would argue to sort the array O(n log n), space O(n), and then perform the O(n) search. However both these techniques would require you to delete from an array, which is O(n).
C.) If order doesn't matter, then the "simplest" thing to do would be to add them to a tree that doesn't allow repeats (like a set), insertion O(log n), and then traverse the tree to write out the results into the existing array. Space complexity goes up to O(n), but you stay at O(log n) + O(n)
public void removeduplicates(int[] array)
{
int i, j, new_length = 1;
for (i = 1; i < array.Length; i++)
{
for (j = 0; j < new_length; j++)
{
if (array[i] == array[j])
break;
}
/* if none of the values in index[0..j] of array is not same as array[i],
then copy the current value to corresponding new position in array */
if (j == new_length)
array[new_length++] = array[i];
}
for (i = 0; i < new_length; i++)
{
Console.WriteLine(array[i]);
}
}
void main()
{
int n,*a,i,j,k;
printf("enter the size of the array:\n");
scanf("%d",&n);
a=(int*)malloc(n*sizeof(int));
printf("enter the elements:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
for(k=j;k<n;k++)
a[k]=a[k+1];
n--;
j--;
}
}
}
for(i=0;i<n;i++)
printf(" %d",a[i]);
}
first, you'd have a set which holds the integers.
second, you'd have to put the integers of the array into the set.
third, you can have the numbers which is unique.
Traverse the array once. While traversing, keep track of count of all elements in the array using a temp array count[] of size n, when you see an element whose count is already set, then that element is duplicate :
if(count[arr[i]]==1) then that element is duplicate...
There are only two good solutions for this problem.
- oOZz June 19, 20131. Using hashtable as @zbesst and @coding.arya suggested, which is O(n) time and space
2.Sorting solution which is O(n lg n) time and O(1) space.
I saw someone -1'd the posts of @zbesst and @coding.arya. When people do that, they should at least have the courtesy to write the reason. I'll +1 you guys.