ION idea Interview Question Developer Program Engineers
0of 0 votescreate an array and remove all the duplicates in the array.no duplicates are allowed in the array.display the contents of the array finally after the duplicates are removed.
Country: India
Interview Type: Written Test
this is a better solution for a array that does not allow duplicates and if any this code removes the duplicates.
import java.io.*;
import java.util.*;
class Array
{
public static void main(String...args)
{
int[] arr1={1,2,2,4,5,4,6,8};
TreeSet <Integer> ts=new TreeSet<Integer>();
for(int i=0;i<arr1.length;i++)
ts.add(new Integer(arr1[i]));
int size=ts.size();
int [] arr=new int[size];
Iterator <Integer>it=ts.iterator();
int j=0;
while(it.hasNext())
{
arr[j]=(Integer)it.next();
j++;
}
for(int x:arr)
{
System.out.println(x);
}
}
}

Here is an solution to this problem. The code is in C#, it uses a Hashtable for fast lookup of values. A bool/bit array can be used for further optimization.
- Irfan Sheikh on May 28, 2012 Edit | Flag Replypublic static int[] RemoveDuplicates(int[] InputArray) { //Declare Hashtable for Array Member Duplicate Check Hashtable tab = new Hashtable(); int i, indexPos = 0; //Duplicate Check Loop for (i = 0; i < InputArray.Length; i++) { //Check if the Array Member has not been added to Hash Table if (!tab.ContainsKey(InputArray[i])) { //Add member tab.Add(InputArray[i], 1); InputArray[indexPos] = InputArray[i]; indexPos++; } } //Set unused porition of array with -1 as for (i = indexPos; i < InputArray.Length; i++) { InputArray[i] = -1; } return InputArray; }