Wednesday, March 16, 2016

Remove Duplicate Elements from an Array.

Remove Duplicate Elements from Array              

a)     Using unique property of Sets which makes problem quite simple.
It is much better than second approach.

b)    Interviewers are more emphasized on second approach as it requires some tricky coding skills.

public class RemoveDuplicateElements {

static int array[] = new int[] { 10, 20, 30, 10, 15, 40, 30, 10, 20, 90, 50 };

     public static void main(String[] args) {
           // Using In-Build Collection API
           System.out.println("Using Approach 1");
           Approach1(array);

           // Using Code approach. Asked in Flipkart interview...
           System.out.println("Using Approach 2");
           Approach2(array);
     }

       // Prefer LinkedHashSet instead of HashSet so as to maintain order

public static void Approach1(int array[]) {
           Set<Integer> set = new LinkedHashSet<Integer>();

           for (int i = 0; i < array.length; i++)
           set.add(array[i]);
           Object[] objectArray = set.toArray();
          
     for (int i = 0; i < objectArray.length; i++)
           System.out.print(objectArray[i] + "\t");
           System.out.println();
     }

     // Replacing duplicate value with last value and decrement the size

     public static void Approach2(int[] array) {
           int sizeArray = array.length;
           for (int i = 0; i < sizeArray; i++) {
                for (int j = i + 1; j < sizeArray; j++) {
                     if (array[i] == array[j]) {
                           array[j] = array[sizeArray - 1];
                           sizeArray--;
                     }
                }
           }
           int newArray[] = Arrays.copyOf(array, sizeArray);
           for (int i = 0; i < newArray.length; i++)
                System.out.print(newArray[i] + "\t");
     }
}

No comments:

Post a Comment