Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

My code which removes the duplicates from an unsorted array is only working in some cases:

public static int[] removeDuplicates(int[] arr) {

 if (arr.length <= 1)

 {

 return arr;

 }

 int lastFound = arr[0];

 int currPos = 1;

 for (int i = 1; i < arr.length; ++i) {

 int num = arr[i];

 if (lastFound != num) 

{

 lastFound = num;

 arr[currPos++] = num;

 }

 }

 return Arrays.copyOf(arr, currPos);

 }

The input is:

int[] arr = {0, 1, 1, 0, 1, 1, 2, 2};

int[] arr2 = removeDuplicates(arr);

It is returning:

arr2 = {0, 1, 0, 1, 2}

It actually should give:

arr2 = {0, 1, 2}

Can somebody help me with this?

1 Answer

0 votes
by (13.1k points)

Your code only looks at the previous value to determine to add a value which means that your code will only work if all the values are in the contiguous array like this:

{1,1,2,2}

To make your code work, you need to record all the elements that you have seen before, not just the ones at the start of the previous run. You can do this:

LinkedHashSet<Integer> set=new LinkedHashSet<>(Arrays.asList(arr));

Or

set.addAll(Arrays.asList(arr));

If you want to return an int array you need to copy the elements back into an array:

int[] result = new int[set.size()];

 int index = 0;

 for (int value : set)

 {

 result[index++] = value;

 }

 return result;

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...