Thursday, September 6, 2012

Removing duplicates from Array in Java

Approach#1 : Using two loops
 ==============================
In this approach we Loop through all elements in the array comparing an item with rest of the elements.

   The outer loop will pick an item one by one and the inner one compares the picked current element with the rest of the elements in the array.

Here is the java implementation.

      public static Object[] RemoveDuplicatesV3(String[] toBeSearched){
            List toBeSearchedasList=Arrays.asList(toBeSearched);
            List toBeSearchedasListback=new ArrayList();
            toBeSearchedasListback.addAll(toBeSearchedasList);
            for(int i=0;i
                  for(int j=i+1;j
                        if(toBeSearchedasListback.get(i).equals(toBeSearchedasListback.get(j))){
                              toBeSearchedasListback.remove(j);
                        }
                  }
            }
            return toBeSearchedasListback.toArray();
      }
 
This involves O(n2) time. Where n is the no of elements in the array.

Approach#2 : Sorting
 ==============================
First sort the array and traverse the array comparing each element with the next element and removing the element if it matches.


public static Object[] RemoveDuplicatesV2(String[] toBeSearched){
            List toBeSearchedasList=Arrays.asList(toBeSearched);
            List toBeSearchedasListback=new ArrayList();
            toBeSearchedasListback.addAll(toBeSearchedasList);
            Collections.sort(toBeSearchedasListback);
            for(int i=0;i
                  System.out.println("in loop");
                  if(i+1 != toBeSearchedasListback.size()
                              && toBeSearchedasListback.get(i).equals(toBeSearchedasListback.get(i+1))){
                        toBeSearchedasListback.remove(i);
                  }
            }
            return toBeSearchedasListback.toArray();
      }
This is better than approach#1
Approach#3 :Using HashMap
 ==============================
Put the element in hashmap while traversing. If it is already present remove it.

public static Object[] RemoveDuplicates(String[] toBeSearched){
            Hashtable original=new Hashtable();
            for(String current : toBeSearched){
                  if(original.get(current)!=null)
                        original.put(current, current);
            }
            return original.keySet().toArray();
      }
 This is best compared to first 2