Hey guys,
So I have been practicing some common interview questions and have been stumped on one. I got asked this a few weeks ago at a job interview and I failed pretty miserably on it. It is removing duplicates in an array. The problem is as follows:
"Given an array of integers remove the duplicates in the array without using an extra buffer to hold the contents".
I was told I could not use any collections such as a Hashtable or an ArrayList but I COULD use a boolean array. Now first of all I know for a fact arrays in C# are a fixed size so basically you need to shift the contents up and write over the duplicates. I have been trying to solve this problem but cannot come up with a solution!
static int[] removeDupes(int[] array)
{
//Assumes ASCII characters
bool[] boolArray = new bool[256];
int i = 0, len = array.Length - 1;
while (i < len)
{
//Dupe found
if (boolArray[(char)array[i]])
{
//write next element in array to current element
array[i] = array[i + 1];
i--;
}
else
{
//If letter is encountered for first time assign set it to true
boolArray[(char)array[i]] = true;
}
i++;
}
return array;
}
So this effectively 'works' in the sense that it removes the duplicate but it ALWAYS prints out the last value in the array twice. So for example if I have an array with 1,2,2,3,4,5. It will return 1,2,3,4,5,5.
Any ideas on how to solve this??