Array remove duplicate elements

59,940

Solution 1

Check every element against every other element

The naive solution is to check every element against every other element. This is wasteful and yields an O(n2) solution, even if you only go "forward".

Sort then remove duplicates

A better solution is sort the array and then check each element to the one next to it to find duplicates. Choose an efficient sort and this is O(n log n).

The disadvantage with the sort-based solution is order is not maintained. An extra step can take care of this however. Put all entries (in the unique sorted array) into a hashtable, which has O(1) access. Then iterate over the original array. For each element, check if it is in the hash table. If it is, add it to the result and delete it from the hash table. You will end up with a resultant array that has the order of the original with each element being in the same position as its first occurrence.

Linear sorts of integers

If you're dealing with integers of some fixed range you can do even better by using a radix sort. If you assume the numbers are all in the range of 0 to 1,000,000 for example, you can allocate a bit vector of some 1,000,001. For each element in the original array, you set the corresponding bit based on its value (eg a value of 13 results in setting the 14th bit). Then traverse the original array, check if it is in the bit vector. If it is, add it to the result array and clear that bit from the bit vector. This is O(n) and trades space for time.

Hash table solution

Which leads us to the best solution of all: the sort is actually a distraction, though useful. Create a hashtable with O(1) access. Traverse the original list. If it is not in the hashtable already, add it to the result array and add it to the hash table. If it is in the hash table, ignore it.

This is by far the best solution. So why the rest? Because problems like this are about adapting knowledge you have (or should have) to problems and refining them based on the assumptions you make into a solution. Evolving a solution and understanding the thinking behind it is far more useful than regurgitating a solution.

Also, hash tables are not always available. Take an embedded system or something where space is VERY limited. You can implement an quick sort in a handful of opcodes, far fewer than any hash table could be.

Solution 2

If you don't need to keep the original object you can loop it and create a new array of unique values. In C# use a List to get access to the required functionality. It's not the most attractive or intelligent solution, but it works.

int[] numbers = new int[] {1,2,3,4,5,1,2,2,2,3,4,5,5,5,5,4,3,2,3,4,5};
List<int> unique = new List<int>();

foreach (int i in numbers)
     if (!unique.Contains(i))
          unique.Add(i);

unique.Sort();
numbers = unique.ToArray();

Solution 3

This can be done in amortized O(n) using a hashtable-based set.

Psuedo-code:

s := new HashSet
c := 0
for each el in a
  Add el to s.
    If el was not already in s, move (copy) el c positions left.
    If it was in s, increment c. 

Solution 4

Treat numbers as keys.

for each elem in array:
if hash(elem) == 1 //duplicate
  ignore it
  next
else
  hash(elem) = 1
  add this to resulting array 
end
If you know about the data like the range of numbers and if it is finite, then you can initialize that big array with ZERO's.
array flag[N] //N is the max number in the array
for each elem in input array:
  if flag[elem - 1] == 0
    flag[elem - 1] = 1
    add it to resulatant array
  else
    discard it //duplicate
  end

Solution 5

    indexOutput = 1;
    outputArray[0] = arrayInt[0];
    int j;
    for (int i = 1; i < arrayInt.length; i++) {            
        j = 0;
        while ((outputArray[j] != arrayInt[i]) && j < indexOutput) {
            j++;
        }
        if(j == indexOutput){
           outputArray[indexOutput] = arrayInt[i];
           indexOutput++;
        }         
    }
Share:
59,940
mohit
Author by

mohit

Updated on August 21, 2020

Comments

  • mohit
    mohit over 3 years

    I have an unsorted array, what is the best method to remove all the duplicates of an element if present?

    e.g:

    a[1,5,2,6,8,9,1,1,10,3,2,4,1,3,11,3]
    

    so after that operation the array should look like

     a[1,5,2,6,8,9,10,3,4,11]
    
  • pascal
    pascal almost 14 years
    In the question, the resulting array appears to preserve the order of the input array.
  • rbrito
    rbrito about 9 years
    One should make it clear that hashtables only give you expected constant time, not guaranteed constant time.
  • Gökhan Akduğan
    Gökhan Akduğan about 8 years
    While hashtable does not let you to add duplicate items, if you add all of the numbers in hashtable, and then simply print it , you can reach at the same result. what is the point above to use some if conditions and makes the logic more complicated?
  • Szymon Brych
    Szymon Brych over 6 years
    @GökhanAkduğan The most apparent reasons that have been mentioned: significance of ordering, lack of hash table availability, strong space constraints.
  • Rudy Velthuis
    Rudy Velthuis over 5 years
    Why remove from the hashtable if you found a duplicate? Duplicates can also mean triplets, quadruplets etc. I would not remove the value from the hashtable.
  • Justin Meiners
    Justin Meiners about 2 years
    I don't know that the hash table is by far the best, even though it's theoretical complexity is. Sorting is very efficient and cache friendly. Just consider all the complexity in hash tables of handling collisions.