OneBite.Dev - Coding blog in a bite size

Remove Duplicates From An Array In C++

Code snippet for how to Remove Duplicates From An Array In C++ with sample and detail explanation

In the realm of programming, specifically in C++, a common task you might encounter is removing duplicates from an array. This article will provide a simple step-by-step tutorial for beginners on how to perform this operation programmatically.

Code snippet: Removing Duplicates from an Array

Below is a basic C++ code for removing duplicates from an array:

#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;
}

This program will output 1 2 3 4 5, which is the array after removing the duplicates.

Code Explanation: Removing Duplicates from an Array

Here is a step-by-step explanation of the above code snippet.

Firstly, we include the iostream library which allows us to perform input and output operations. The using namespace std line allows us to use elements of the standard (std) namespace without qualifying them fully with std::.

The removeDuplicates function takes an array and its length as inputs and modifies the array to remove any duplicates, returning the new length of the array.

Inside this function, we first check if the array length n is zero or one. If it is, we return n because an array of this size can’t have duplicates.

We then create a temporary array temp of size n.

We loop through the array, comparing each element to the next one. If they are not the same, we place the element in the temporary array and increment the counter j.

After finishing the loop, we overwrite the original array with the elements of the temporary array, effectively removing all duplicates.

The main function is where the program starts execution. We define an array with duplicate elements and calculate its length. We then call the removeDuplicates function with the array and its length as parameters, and print out the elements of the array after the removal of duplicates.

And that’s it! You have successfully created a program to remove duplicates from an array in C++.

c-plus-plus