Given a sorted array arr[] of size N, the task is to remove the duplicate elements from the array.
Examples:
Input: arr[] = {2, 2, 2, 2, 2}
Output: arr[] = {2}
Explanation: All the elements are 2, So only keep one instance of 2.
Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output: arr[] = {1, 2, 3, 4, 5}
Naive Approach (Using extra space):
The idea to solve the problem is to
Create a new array and store the unique elements in the new array. For checking duplicate elements, just check two adjacent elements are equal or not because the array is sorted.
Follow the steps mentioned below to implement the idea:
- Create an auxiliary array temp[] to store unique elements.
- Traverse input array and one by one copy unique elements of arr[] to temp[].
- Also, keep track of the count of unique elements. Let this count be j.
- Copy j elements from temp[] to arr[] and return j.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int removeDuplicates( int arr[], int n)
{
if (n == 0 || n == 1)
return n;
int temp[n];
int j = 0;
for ( int i = 0; i < n - 1; i++)
if (arr[i] != arr[i + 1])
temp[j++] = arr[i];
temp[j++] = arr[n - 1];
for ( int i = 0; i < j; i++)
arr[i] = temp[i];
return j;
}
int main()
{
int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
n = removeDuplicates(arr, n);
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
return 0;
}
|
C
#include <stdio.h>
int removeDuplicates( int arr[], int n)
{
if (n == 0 || n == 1)
return n;
int temp[n];
int j = 0;
for ( int i = 0; i < n - 1; i++)
if (arr[i] != arr[i + 1])
temp[j++] = arr[i];
temp[j++] = arr[n - 1];
for ( int i = 0; i < j; i++)
arr[i] = temp[i];
return j;
}
int main()
{
int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
n = removeDuplicates(arr, n);
for ( int i = 0; i < n; i++)
printf ( "%d " , arr[i]);
return 0;
}
|
Java
class Main {
static int removeDuplicates( int arr[], int n)
{
if (n == 0 || n == 1 )
return n;
int [] temp = new int [n];
int j = 0 ;
for ( int i = 0 ; i < n - 1 ; i++)
if (arr[i] != arr[i + 1 ])
temp[j++] = arr[i];
temp[j++] = arr[n - 1 ];
for ( int i = 0 ; i < j; i++)
arr[i] = temp[i];
return j;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 };
int n = arr.length;
n = removeDuplicates(arr, n);
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
}
}
|
Python3
def removeDuplicates(arr, n):
if n = = 0 or n = = 1 :
return n
temp = list ( range (n))
j = 0
for i in range ( 0 , n - 1 ):
if arr[i] ! = arr[i + 1 ]:
temp[j] = arr[i]
j + = 1
temp[j] = arr[n - 1 ]
j + = 1
for i in range ( 0 , j):
arr[i] = temp[i]
return j
if __name__ = = '__main__' :
arr = [ 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 ]
n = len (arr)
n = removeDuplicates(arr, n)
for i in range (n):
print ( "%d" % (arr[i]), end = " " )
|
C#
using System;
class GFG {
static int removeDuplicates( int []arr, int n)
{
if (n == 0 || n == 1)
return n;
int []temp = new int [n];
int j = 0;
for ( int i = 0; i < n - 1; i++)
if (arr[i] != arr[i+1])
temp[j++] = arr[i];
temp[j++] = arr[n-1];
for ( int i = 0; i < j; i++)
arr[i] = temp[i];
return j;
}
public static void Main ()
{
int []arr = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = arr.Length;
n = removeDuplicates(arr, n);
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
}
|
Javascript
<script>
function removeDuplicates(arr, n)
{
if (n==0 || n==1)
return n;
var temp = new Array(n);
var j = 0;
for ( var i=0; i<n-1; i++)
if (arr[i] != arr[i+1])
temp[j++] = arr[i];
temp[j++] = arr[n-1];
for ( var i=0; i<j; i++)
arr[i] = temp[i];
return j;
}
var arr = [1, 2, 2, 3, 4, 4, 4, 5, 5];
var n = arr.length;
n = removeDuplicates(arr, n);
for ( var i=0; i<n; i++)
document.write( arr[i]+ " " );
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach using Set :
By using set to remove duplicates from an input array and update the array with unique elements and finally return the count of unique elements.
- Use set to collect unique elements from the array.
- Updates the array with unique elements, modifying the size.
- Prints the modified array, now containing only unique elements.
C++
#include <bits/stdc++.h>
using namespace std;
int removeDuplicates( int arr[], int n) {
if (n <= 1)
return n;
set< int > uniqueElements;
for ( int i = 0; i < n; ++i) {
uniqueElements.insert(arr[i]);
}
int index = 0;
for ( auto it = uniqueElements.begin(); it != uniqueElements.end(); ++it) {
arr[index++] = *it;
}
return uniqueElements.size();
}
int main() {
int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = sizeof (arr) / sizeof (arr[0]);
n = removeDuplicates(arr, n);
for ( int i = 0; i < n; i++) {
cout << arr[i] << " " ;
}
return 0;
}
|
Java
import java.util.HashSet;
import java.util.Set;
public class RemoveDuplicates {
static int removeDuplicates( int [] arr, int n) {
if (n <= 1 )
return n;
Set<Integer> uniqueElements = new HashSet<>();
for ( int i = 0 ; i < n; ++i) {
uniqueElements.add(arr[i]);
}
int index = 0 ;
for ( int element : uniqueElements) {
arr[index++] = element;
}
return uniqueElements.size();
}
public static void main(String[] args) {
int [] arr = { 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 };
int n = arr.length;
n = removeDuplicates(arr, n);
for ( int i = 0 ; i < n; i++) {
System.out.print(arr[i] + " " );
}
}
}
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Efficient Approach:
This problem can be solved efficiently just by maintaining a separate index for the same array as maintained for different array in the previous method and replacing that element with the unique element.
Follow the steps mentioned below to implement the idea:
- Traverse input array from i = 0 to N:
- Keep track of the count of unique elements. Let this count be j.
- Swap arr[j] with arr[i].
- At last, return j.
Below is the implementation of the above approach.
C++
#include<bits/stdc++.h>
using namespace std;
int removeDuplicates( int arr[], int n)
{
if (n==0 || n==1)
return n;
int j = 0;
for ( int i=0; i < n-1; i++)
if (arr[i] != arr[i+1])
arr[j++] = arr[i];
arr[j++] = arr[n-1];
return j;
}
int main()
{
int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = sizeof (arr) / sizeof (arr[0]);
n = removeDuplicates(arr, n);
for ( int i=0; i<n; i++)
cout << arr[i] << " " ;
return 0;
}
|
Java
class Main
{
static int removeDuplicates( int arr[], int n)
{
if (n == 0 || n == 1 )
return n;
int j = 0 ;
for ( int i = 0 ; i < n- 1 ; i++)
if (arr[i] != arr[i+ 1 ])
arr[j++] = arr[i];
arr[j++] = arr[n- 1 ];
return j;
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 };
int n = arr.length;
n = removeDuplicates(arr, n);
for ( int i= 0 ; i<n; i++)
System.out.print(arr[i]+ " " );
}
}
|
Python3
def remove_duplicates(arr):
n = len (arr)
if n = = 0 or n = = 1 :
return n
j = 0
for i in range (n - 1 ):
if arr[i] ! = arr[i + 1 ]:
arr[j] = arr[i]
j + = 1
arr[j] = arr[n - 1 ]
return j + 1
if __name__ = = "__main__" :
arr = [ 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 ]
n = len (arr)
n = remove_duplicates(arr)
for i in range (n):
print (arr[i], end = " " )
|
C#
using System;
class GfG {
static int removeDuplicates( int []arr, int n)
{
if (n == 0 || n == 1)
return n;
int j = 0;
for ( int i = 0; i < n - 1; i++)
if (arr[i] != arr[i + 1])
arr[j++] = arr[i];
arr[j++] = arr[n - 1];
return j;
}
public static void Main ()
{
int []arr = {1, 2, 2, 3, 4, 4,
4, 5, 5};
int n = arr.Length;
n = removeDuplicates(arr, n);
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
}
|
Javascript
<script>
function removeDuplicates(arr , n) {
if (n == 0 || n == 1)
return n;
var j = 0;
for (i = 0; i < n - 1; i++)
if (arr[i] != arr[i + 1])
arr[j++] = arr[i];
arr[j++] = arr[n - 1];
return j;
}
var arr = [ 1, 2, 2, 3, 4, 4, 4, 5, 5 ];
var n = arr.length;
n = removeDuplicates(arr, n);
for (i = 0; i < n; i++)
document.write(arr[i] + " " );
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Fastest Efficient Approach: Using Binary Search
The problem requires us to remove duplicate elements from a sorted array, i.e., we need to keep only one copy of each element in the array. Since the array is sorted, all duplicate elements will be adjacent to each other, so we can easily remove them by shifting the subsequent elements of the array to the left.
We can use two pointers i and j, where i points to the last unique element found so far, and j points to the current element being examined. If nums[i] and nums[j] are equal, we just increment j. Otherwise, we increment i and copy nums[j] to nums[i]. At the end, we return i+1, which represents the length of the modified array.
We Would be using Binary Search to solve the particular problem in the fastest way.
Implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int binarySearch(vector< int > &nums, int low, int high, int val){
int n = nums.size();
int res = -1;
while (low<=high){
int mid = low + (high-low)/2;
if (nums[mid] <= val) low = mid+1;
else {
res = mid;
high = mid-1;
}
}
if (res == -1) return n;
return res;
}
int removeDuplicates(vector< int >& nums) {
int n = nums.size();
int idx = 0;
while (idx != n){
int i = binarySearch(nums,idx+1,n-1,nums[idx]);
if (i == n) return idx+1;
idx++;
nums[idx] = nums[i];
}
return idx+1;
}
int main()
{
vector< int > arr{1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = removeDuplicates(arr);
for ( int i=0; i<n; i++)
cout << arr[i] << " " ;
return 0;
}
|
Java
import java.util.Arrays;
public class GFG {
public static int binarySearch( int [] nums, int low, int high, int val) {
int n = nums.length;
int res = - 1 ;
while (low <= high) {
int mid = low + (high - low) / 2 ;
if (nums[mid] <= val)
low = mid + 1 ;
else {
res = mid;
high = mid - 1 ;
}
}
if (res == - 1 )
return n;
return res;
}
public static int removeDuplicates( int [] nums) {
int n = nums.length;
int idx = 0 ;
while (idx != n) {
int i = binarySearch(nums, idx + 1 , n - 1 , nums[idx]);
if (i == n)
return idx + 1 ;
idx++;
nums[idx] = nums[i];
}
return idx + 1 ;
}
public static void main(String[] args) {
int [] arr = { 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 };
int n = removeDuplicates(arr);
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
}
}
|
Python3
def binary_search(nums, low, high, val):
n = len (nums)
res = - 1
while low < = high:
mid = low + (high - low) / / 2
if nums[mid] < = val:
low = mid + 1
else :
res = mid
high = mid - 1
if res = = - 1 :
return n
return res
def remove_duplicates(nums):
n = len (nums)
idx = 0
while idx ! = n:
i = binary_search(nums, idx + 1 , n - 1 , nums[idx])
if i = = n:
return idx + 1
idx + = 1
nums[idx] = nums[i]
return idx + 1
if __name__ = = "__main__" :
arr = [ 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 ]
n = remove_duplicates(arr)
for i in range (n):
print (arr[i], end = " " )
|
C#
using System;
using System.Collections.Generic;
class Program
{
static int BinarySearch(List< int > nums, int low, int high, int val)
{
int n = nums.Count;
int res = -1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (nums[mid] <= val)
low = mid + 1;
else
{
res = mid;
high = mid - 1;
}
}
if (res == -1)
return n;
return res;
}
static int RemoveDuplicates(List< int > nums)
{
int n = nums.Count;
int idx = 0;
while (idx != n)
{
int i = BinarySearch(nums, idx + 1, n - 1, nums[idx]);
if (i == n)
return idx + 1;
idx++;
nums[idx] = nums[i];
}
return idx + 1;
}
static void Main()
{
List< int > arr = new List< int > { 1, 2, 2, 3, 4, 4, 4, 5, 5 };
int n = RemoveDuplicates(arr);
for ( int i = 0; i < n; i++)
{
Console.Write(arr[i] + " " );
}
Console.WriteLine();
}
}
|
Javascript
function binarySearch(nums, low, high, val) {
let res = -1;
while (low <= high) {
let mid = Math.floor(low + (high - low) / 2);
if (nums[mid] <= val) low = mid + 1;
else {
res = mid;
high = mid - 1;
}
}
if (res === -1) return nums.length;
return res;
}
function removeDuplicates(nums) {
let n = nums.length;
let idx = 0;
while (idx !== n) {
let i = binarySearch(nums, idx + 1, n - 1, nums[idx]);
if (i === n) return idx + 1;
idx++;
nums[idx] = nums[i];
}
return idx + 1;
}
let arr = [1, 2, 2, 3, 4, 4, 4, 5, 5];
let n = removeDuplicates(arr);
for (let i = 0; i < n; i++) {
console.log(arr[i]);
}
|
Output:
1 2 3 4 5
Time Complexity: O(N) , in the worst case we will traverse whole array when each element of array is unique.
Auxiliary Space: O(1),No extra space is used
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
29 Nov, 2023
Like Article
Save Article