Open In App

C++ Program To Remove Duplicates From Sorted Array

Last Updated : 22 Sep, 2025
Comments
Improve
Suggest changes
Like Article
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 the input array arr[] .
    Copy each unique element to temp[].
    Keep track of the count of unique elements (j).
  3. Copy the first j elements from temp[] back to arr[].
  4. Return j as the new size.
C++
#include <iostream>
using namespace std;

int removeDuplicates(int arr[], int n)
{
    // Return, if array is empty or contains a single element
    if (n == 0 || n == 1)
        return n;

    int temp[n];

    // Start traversing elements
    int j = 0;

    // If current element is not equal to next element then store that current element
    for (int i = 0; i < n - 1; i++)
        if (arr[i] != arr[i + 1])
            temp[j++] = arr[i];

    temp[j++] = arr[n - 1];

    // Modify original array
    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 

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;

    // To store index of next unique element
    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);

    // Print updated array
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";

    return 0;
}

Output
1 2 3 4 5 

Output: 

1 2 3 4 5

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


Article Tags :

Explore