Open In App

C++ Program To Remove Duplicates From Sorted Array

Last Updated : 17 Jan, 2023
Comments
Improve
Suggest changes
2 Likes
Like
Report

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)

  1. Create an auxiliary array temp[] to store unique elements.
  2. 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.
  3. Copy j elements from temp[] to arr[] and return j

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.

Output: 

1 2 3 4 5

Time Complexity : O(n) 
Auxiliary Space : O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads