Remove Duplicate from Array with C#
This is one of the most frequently asked interview question. This question usually asked for interview of Software Engineer/Test Engineer in Microsoft, Google, Amazon.
We’ve 3 simple solution for this question.
/// <summary>
/// This method removes duplicate from integer array
/// </summary>
/// <param name="a">input array</param>
/// <returns>integer array with no duplicate</returns>
public int[] RemoveUsingHash(int[] a)
{
Hashtable ht = new Hashtable();
for (int i = 0; i < a.Length; i++)
{
if (!ht.ContainsKey(a[i]))
{
ht.Add(a[i], a[i]);
}
}
int[] output = new int[ht.Count];
int j = 0;
foreach (int item in ht.Keys)
{
output[j++] = item;
}
return output;
} |
/// <summary>
/// This method uses array (bucket) of integer
/// </summary>
/// <param name="a">input integer array</param>
/// <returns>array of integers without duplicate content on it.</returns>
public int[] BucketRemove(int[] a)
{
int[] bucket = new int[256];
int count = 0;
for (int i = 0; i < a.Length; i++)
{
if (bucket[a[i]] != 1)
{
bucket[a[i]] = 1;
count++;
}
}
int[] output = new int[count];
int j = 0;
for (int i = 0; i < bucket.Length; i++)
{
if (bucket[i] == 1)
{
output[j++] = i;
}
}
return output;
} |
This method only works for sorted array. You can either return same array (duplicate content will move to last part of array) or last index of array which is length of array without duplicate element.
/// <summary>
/// Removes duplicate in sorted array
/// </summary>
/// <param name="a">array of integers</param>
/// <returns>array of integers with no duplicate content (duplicate content moved to last part of array.)</returns>
public int[] RemoveDuplicate(int[] a)
{
int j = 0;
for (int i = 1; i < a.Length; i++)
{
if (a[j] != a[i])
{
a[++j] = a[i];
}
}
return a;
} |
Testing these methods:
int[] input = new int[] { 1, 2, 3, 4, 4, 5, 5, 6, 7 };
int[] a = BucketRemove(input);
foreach (int i in a)
{
Console.Write(i + " ");
}
Console.WriteLine();
int[] b =RemoveUsingHash(input);
foreach (int i in a)
{
Console.Write(i + " ");
}
Console.WriteLine();
int[] c = RemoveDuplicate(input);
foreach (int i in a)
{
Console.Write(i + " ");
} |
OUTPUT:
1 2 3 4 5 6 7
1 2 3 4 5 6 7
1 2 3 4 5 6 7 |
Related Posts:
.NET, Array, C#, Remove Duplicate
0 Comments For This Post
1 Trackbacks For This Post
January 15th, 2010 at 8:08 am
Title…
Very interesting post. I would like to link back to it….
Leave a Reply
You must be logged in to post a comment.