Remove Duplicates From Sorted Array

Given a sorted array, we have to write a code to remove the duplicates in-place such that each element appear only once and return the new length.

For this problem, we don’t have to use extra space. As we have to remove duplicates in-place (In O(1)).

Note that we have to return the new length, make sure to change the original array as well in place

For example:

Input : { 1, 2, 2, 3, 4, 4, 5, 6, 6, 7 }

Output: 7

Our function should return length 7 with first seven elements of array are {1, 2, 3, 4, 5, 6, 7}. It doesn’t matter what you leave beyond the returned length

Remove Duplicates From Sorted Array

In this tutorial, I am going to discuss how we can efficiently remove the duplicate elements from a sorted array and it’s java code.

In an interview, I have seen many people try to solve this problem using Set (Set does not allow duplicates). But before using Set or any other data structure first clarify with your interviewer whether extra space is allowed or not.

Let me clarify again, we have to solve this problem in a single traversal and without using any extra space.

Programming Video Tutorials

Remove Duplicates from Sorted Array – Java Code

In the problem statement it is already mentioned that the array is sorted. To solve this problem we can declare two indexes i an j to remove duplicate elements from an array.

Traverse an array and increment the value of i at each step. The value of index j is incremented when arr[i] is not equal to arr[i+1]. Repeat this step until the array is traversed completely.

The time complexity of this approach is O(n) and it’s space complexity is O(1).

Remove duplicates from an unsorted array

Remove duplicates from sorted linked list

Remove Duplicates from Sorted Array InterviewBit Solution

Similar problem is present in an InterviewBit. In function argument instead of array it is list of integer. Let’s write it’s code.

Segregate Os and 1s in an array

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.