Sitemap
Devhub

Devhub

Leetcode:26 — Remove Duplicates from sorted Array

1 min readAug 22, 2025

--

Hey Folks. I am back with the classic Leetcode array problem.

Removing duplicates from a sorted Array.

For you reference I will attach the problem link here: https://leetcode.com/problem-list/nfkpb3yh/

It sounds simple when we read the question, but it is a little bit twisted if you have read the question completely.

We don’t directly remove the elements we rearrange them.

Let’s say we have an array [1,1,2,2,3,3,4]

the resultant array should be [1,2,3,4,_,_,_] remember the “_” is just for understanding the requirement we don’t have to replace the elements with “_”.

Get Devhub’s stories in your inbox

Join Medium for free to get updates from this writer.

So here I went with a classic two pointer approach

## Approach:
- Here we go with a simple two pointer approach
- we initialize two pointer i and j and another value to track the last updated index
- we compare the array elements with the index
- when we encounter the different elements we got the unique one
- so we just shift the element at index j to the index of last updated index
public static int getTheUniques(int[] arr){
int i=0, j=1, lastUpdated =1;

while(j<arr.length){
if(arr[i] != arr[j]){
arr[lastUpdated]=arr[j];
i = j;
j++;
lastUpdated++;
}else{
j++;
}
}
for(int k=0;k<lastUpdated;k++){
System.out.print(arr[k]+" "); // just to understand the execution
}
return lastUpdated;
}

I know there has to be a better approach than this let me know if you find one. It was an easy one only I know.

PEACE OUT!!

You can reach out to me through:

www.linkedin.com/in/santhosh-kumar-01a5a8195

https://github.com/santhosh25420

--

--