Thursday, 19 May 2016

Remove duplicate elements from array

Remove duplicate elements from array and don’t use any data structure other than same array.

There may be number of ways to solve this problem. I am going to explain my own way.

Suppose array has elements like {2, 3, 4, 5, 2, 3, 4, 5}.  Following is the pseudo code.

startCounter = 0, endCounter = arrayLength-1 = 7

Step 1: Check the elements from startCounter+1 to endCounter, if any element matcher to arr[startCouter], swap that element to arr[endCounter]. Decrement endCounter.

Step 2: Repeat step 1, until startCounter < endCounter.


Step 3: Final result should be the elements in array from 0 to startCounter.
import java.util.Objects;

public class DuplicateRemover {
 /**
  * Return new array by removing duplicate elements
  * 
  * @return
  */
 public static int[] removeDuplicates(int arr[]) {
  int[] empty = new int[0];

  if (Objects.isNull(arr) || arr.length == 0) {
   return empty;
  }

  int endCounter = arr.length - 1;
  int startCounter = 0;

  for (startCounter = 0; startCounter <= endCounter; startCounter++) {
   for (int j = endCounter; j > startCounter; j--) {
    if (arr[j] == arr[startCounter]) {
     int temp = arr[endCounter];
     arr[endCounter] = arr[j];
     arr[j] = temp;
     endCounter--;
    }
   }
  }

  int b[] = new int[startCounter];
  for (int i = 0; i < startCounter; i++) {
   b[i] = arr[i];
  }

  return b;
 }

}

import org.junit.Assert;
import org.junit.Test;

public class DuplicateRemoverTest {

 @Test
 public void test() {
  int arr1[] = {};
  int arr2[] = { 1 };
  int arr3[] = { 1, 1 };
  int arr4[] = { 1, 1, 1 };
  int arr5[] = { 1, 2, 3, 4, 1, 2, 3, 4 };
  int arr6[] = { 1, 1, 2, 2, 3, 3, 4, 4 };

  int expected1[] = new int[0];
  int expected2[] = { 1 };
  int expected3[] = { 1 };
  int expected4[] = { 1 };
  int expected5[] = { 1, 2, 3, 4 };
  int expected6[] = { 1, 4, 2, 3 };

  Assert.assertArrayEquals(DuplicateRemover.removeDuplicates(arr1),
    expected1);
  Assert.assertArrayEquals(DuplicateRemover.removeDuplicates(arr2),
    expected2);
  Assert.assertArrayEquals(DuplicateRemover.removeDuplicates(arr3),
    expected3);
  Assert.assertArrayEquals(DuplicateRemover.removeDuplicates(arr4),
    expected4);
  Assert.assertArrayEquals(DuplicateRemover.removeDuplicates(arr5),
    expected5);
  Assert.assertArrayEquals(DuplicateRemover.removeDuplicates(arr6),
    expected6);
 }
}



No comments:

Post a Comment