C++ Program To Remove Duplicates From Sorted Array
Given a sorted array, the task is to remove the duplicate elements from the array.
Examples:
Input: arr[] = {2, 2, 2, 2, 2}
Output: arr[] = {2}
new size = 1
Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output: arr[] = {1, 2, 3, 4, 5}
new size = 5
Method 1: (Using extra space)
- 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 count of unique elements. Let this count be j.
- Copy j elements from temp[] to arr[] and return j
C++
#include <iostream>
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;
}
|
Output:Â Â
1 2 3 4 5
Time Complexity: O(n)Â
Auxiliary Space: O(n)
Method 2: (Constant extra space)Â
Just maintain a separate index for same array as maintained for different array in Method 1.
C++
#include<iostream>
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;
}
|
Output:Â
1 2 3 4 5
Time Complexity : O(n)Â
Auxiliary Space : O(1)
Last Updated :
17 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...