# LeetCode – Remove Duplicates from Sorted Array (Java)

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory.

For example, given input array A = [1,1,2], your function should return length = 2, and A is now [1,2].

Thoughts

The problem is pretty straightforward. It returns the length of array with unique elements, but the original array need to be changed also. This problem should be reviewed with Remove Duplicates from Sorted Array II.

Solution 1

```// Manipulate original array public static int removeDuplicatesNaive(int[] A) { if (A.length < 2) return A.length;   int j = 0; int i = 1;   while (i < A.length) { if (A[i] == A[j]) { i++; } else { j++; A[j] = A[i]; i++; } }   return j + 1; }```

This method returns the number of unique elements, but does not change the original array correctly. For example, if the input array is {1, 2, 2, 3, 3}, the array will be changed to {1, 2, 3, 3, 3}. The correct result should be {1, 2, 3}. Because array's size can not be changed once created, there is no way we can return the original array with correct results.

Solution 2

```// Create an array with all unique elements public static int[] removeDuplicates(int[] A) { if (A.length < 2) return A;   int j = 0; int i = 1;   while (i < A.length) { if (A[i] == A[j]) { i++; } else { j++; A[j] = A[i]; i++; } }   int[] B = Arrays.copyOf(A, j + 1);   return B; }   public static void main(String[] args) { int[] arr = { 1, 2, 2, 3, 3 }; arr = removeDuplicates(arr); System.out.println(arr.length); }```

In this method, a new array is created and returned.

Solution 3

If we only want to count the number of unique elements, the following method is good enough.

```// Count the number of unique elements public static int countUnique(int[] A) { int count = 0; for (int i = 0; i < A.length - 1; i++) { if (A[i] == A[i + 1]) { count++; } } return (A.length - count); }   public static void main(String[] args) { int[] arr = { 1, 2, 2, 3, 3 }; int size = countUnique(arr); System.out.println(size); }```
Category >> Algorithms
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• Avinash Ujjwal

Here is an option to remove duplicates for sorted or unsorted array using Java 8 stream API.

public static int[] removeDuplicates(int[] array) {
return IntStream.of(array).distinct().toArray();
}

• Thierry E N

public static int removeDuplicates(int[] nums) {
int size=0;
if(nums.length==1) return 1;
if(nums.length==0) return 0;
for(int i=0; i<nums.length-1; i++){
if(nums[i]!=nums[i+1]){
nums[++size]=nums[i+1];
}
}
return ++size;
}

• Arafath Ali

Will this also work ?

public static int removeMyDups(int[] arr){
if(arr.length<1)
return 0;

int count=1;
for(int i=0;i <(arr.length)-1;i++){
if(arr[i] != arr[i+1]){
count++;
}
}
return count;
}

• Dileep Buddaraju

Another alternative to find unique size of array (Solution 3).

public static int countUnique(int[] A) {

LinkedHashSet output = new LinkedHashSet();

for(int i =0; i<= A.length – 1 ; i++)
{
output.add(A[i]);
}

return output.size();

}

• Gokhan

it does not handle the case when your input is like :

int arr [] = {1,2,2,3,3,4,4,5,5,5,3,2,1,4,8,8,1};

it returns you B array :

[1, 2, 3, 4, 5, 3, 2, 1, 4, 8, 1]

• I tried to solve it on LeetCode using a HashSet. My solution was accepted, but probably it ain’t that optimal.

public class Solution {
public int removeDuplicates(int[] A) {

HashSet mySet = new HashSet();

for (int i=0; i<A.length;i++) mySet.add(A[i]) ;

int j = 0 ;

for(int i : mySet) {

A[j] = i;

j++;

}
for(int i=j; i<A.length;i++) A[i] = Integer.MAX_VALUE;

Arrays.sort(A) ;

return mySet.size();

}

}

• Ken

It seems like Solution 1 is the only solution that addresses the original problem – Solution 2 allocates a new array and Solution 3 only counts the number of duplicates. Also, solution 1 is labeled “naive”, but it seems to have the best possible runtime – O(n).

• jitendra varshney from K.I.E.T

this as simle you can think just paste on notepad ..than understand the code ..

• jitendra varshney from K.I.E.T

package arrays;

import java.io.*;

import java.util.Arrays;

public class DuplicateRemove {

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println(“enter how many number do you want to sort”);

String str=br.readLine();

int n=Integer.parseInt(str);

int num[]=new int[n];

System.out.println(“enter your numbers”);

for(int i=0;i<n;i++)

{

num[i]=Integer.parseInt(br.readLine());

}

for(int i=0;i<n;i++)

{

System.out.println(num[i]);

}

Arrays.sort(num);

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

{

if(num[i]!=num[i-1])

{

System.out.println("duplicate"+num[i]);

}

}

}

}

• I don’t see why Solution 2 is listed here since it seems to be in direct contradiction of the original requirements (do NOT allocate a new array, constant memory use). Listing it here only confuses the reader.

• Guilherme Santos

But your solution won’t work in this case:

a=(3,3,4,5,5), as the index of 4 is 2 != 4 and you make the decision to ignore the duplicates in the upper half (5 and 5).

• If the sorted array has 5 elements and the middle element is 4 and the first two elements are duplicates, the array looks like (3,3,4,5,6). The index of the middle element is ‘2’ which is not equal to 4. So the duplicate element is in the lower half of the array.

• dm

This doesn’t work. What if the middle element is 4 but the first two elements are duplicates…

• sireen

How we can write amethod to return an array after adding elements to the array

• Vivek Venkatesh

We can use the XOR operator too I guess.

The following should work:
``` import java.util.Arrays; public class HelloWorld{ public int[] removeDuplicates(int a[]) { int previousElement = a[0]; int pos = 0; for(int i=1; i < a.length; i++) { int currentElement = a[i]; if((currentElement ^ previousElement) == 0) { // Same Element again } else { previousElement = currentElement; pos++; a[pos] = currentElement; } } return Arrays.copyOf(a, pos+1); } ```

``` ```

``` public static void main(String []args){ int a[] = {1,2,2,2,3,3,3,4,4,5}; int b[] = new HelloWorld().removeDuplicates(a); for(int cur: b) { System.out.println(cur); } } } ```

• Neel Sheyal

Find the middle element of the input array and compare it with its index.

If they are same, the duplicate element(s) will be at the upper half of the array.

Otherwise, it will be at the lower half of the array.
Time complexity = O(nlogn). You can find the code in http://www.algoqueue.com/algoqueue/default/view/3604480/remove-duplicates-in-a-sorted-integer-array-

• ryanlr

Good solution. Mine was wrong, I have corrected it. Thanks!

• Matt Auerbach

Sorry about that– it should be formatted now. Let me know what you think. Seems simpler to me.

• ryanlr

I want to see your solution. Can you put your code inside <pre> <code> tags?

• Matt Auerbach

This solution also works:
``` public static int removeDups(int[] arr){ int count=0; for(int i=0;i<arr.length-1;i++){```

``` if(arr[i] == arr[i+1]){ count++; } } return (arr.length-count); ```

``` } ```