views:

229

answers:

3

Hi,

I received one question "How to delete duplicate entries from an array" Constrain: No new data structure and same array should return only distinct element. So for example If my array is 1,3,3,3,5,55,67,1 then the result should be 1,3,5,55,67

I have solved the problem

    public void DeleteDuplicate(int[] array)
    {
        int l = 0;
        int newPosition = array.Length -1;
        for (int i = 0; i < array.Length; i++)
        {
            for (int j = i + 1; j < array.Length-l; j++)
            {
                if (array[i] == array[j])
                {
                    int temp = array[j];
                    array[j] = array[newPosition];
                    array[newPosition] = temp;
                    newPosition--;
                    l++;
                }
            }
        }
        Array.Resize(ref array, array.Length - l);
    }

I need your opinion whether it is a good algorithm or need to change something.

Thanks, Pritam

+3  A: 

Your code is buggy. Try running it against {1, 1, 1} - I think it will return {1, 1}.

Olexiy
+1 If a duplicate is found, `j` shouldn't be advanced.
Andreas Brinck
+2  A: 

In general, the question whether you have to maintain the relative ordering of the elements. For example, whether it is possible to return {1, 2} for input {2, 1, 2, 1}.

If it is allowed, then the fastest solution will be:

  • sort input array
  • run once through it comparing a[i] with a[i+1] and removing duplicates in O(N)'

The total complexity would be O(N*logN), which is better than N^2 you proposed.

If you must preserve the initial ordering, then I am not ready to propose a solution.

Olexiy
Could you please let me how to delete repeated element. As I have used Array.Resize, in this case when I will compare i with i+1 then if match found then I need to move the i+1 to the end of the array. In this case this will not work. Lets say the array content 1 1 1 3 3 5..then in first step 1 1 3 3 5 1--remove 1 from last -- now the array is 1 1 3 3 5. Now 1 will compare with 3 and the 2nd 1 will not be removed. Please help
Pritam Karmakar
That's definitely possible. You just don't swap elements right away - first you go through array, replace all duplicates by zeroes or some other number which is not present in the array, and only in the end you shift all elements to their respective places in 1 pass through the array.
Olexiy
A: 

Last time I checked C# allowed you to sort 2 arrays by using one for the comparisons and doing the swaps on both.

Here's what you can do:

  • Create an array indices that stores the numbers 0 to N-1.
  • Sort array and indices using array as the key.
  • Find the duplicates and set the indices of duplicates to N+1.
  • Sort array and indices using indices as key.
  • Resize the array to the correct size and presto.

This removes duplicates and preserves ordering.

JPvdMerwe