Program to Remove Duplicate Elements from an Array with examples

In this article, we’ll write a program to remove duplicate elements from an array using C#, C++, Python, and Java examples. 

Understanding the Problem

Before diving into the code, let’s first understand the problem at hand. Duplicate elements in an array are repeated values that can adversely affect the performance and correctness of algorithms. 

The goal is to design a program that efficiently identifies and removes these duplicate elements while maintaining the order of elements in an Array.

C#

C# provides several approaches to handling and writing a program to remove duplicate elements from an array

We will explore two common methods: using HashSet and LINQ.

Method 1: Using HashSet

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] array = { 1, 2, 3, 4, 2, 5, 6, 7, 7, 8 };
        
        // Using HashSet to remove duplicates
        HashSet<int> uniqueSet = new HashSet<int>(array);

        // Displaying the unique elements
        foreach (int element in uniqueSet)
        {
            Console.Write(element + " ");
        }
    }
}

Output:

1 2 3 4 5 6 7 8

Code Explanation:

  • We are using a HashSet to eliminate duplicate elements automatically.
  • The uniqueSet variable holds distinct elements of the array.
  • A foreach loop is used to iterate through and display the unique elements.

Method 2: Using LINQ

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] array = { 1, 2, 3, 4, 2, 5, 6, 7, 7, 8 };
        
        // Using LINQ to remove duplicates
        int[] uniqueArray = array.Distinct().ToArray();

        // Displaying the unique elements
        foreach (int element in uniqueArray)
        {
            Console.Write(element + " ");
        }
    }
}

Output:

1 2 3 4 5 6 7 8 

Method 3: Without using the Inbuilt function.

Below is the C# program to remove duplicate elements from an array without using any inbuilt functions.

using System;

class Program
{
    static void Main()
    {
        int[] array = { 1, 2, 3, 4, 2, 5, 6, 7, 7, 8 };

        // Displaying the original array
        Console.WriteLine("Original Array:");
        DisplayArray(array);

        // Removing duplicates in the array
        int newSize = RemoveDuplicates(array);

        // Displaying the array after removing duplicates
        Console.WriteLine("\nArray After Removing Duplicates:");
        DisplayArray(array, newSize);
    }

    static void DisplayArray(int[] arr, int size = -1)
    {
        if (size == -1)
            size = arr.Length;

        for (int i = 0; i < size; i++)
        {
            Console.Write(arr[i] + " ");
        }
        Console.WriteLine("\n");
    }

    static int RemoveDuplicates(int[] arr)
    {
        int length = arr.Length;

        // Check for an empty array
        if (length == 0)
            return 0;

        // Initialize a variable to keep track of the non-duplicate elements
        int newSize = 1;

        // Loop through the array starting from the second element
        for (int i = 1; i < length; i++)
        {
            bool isDuplicate = false;

            // Check if the current element is a duplicate of any previous elements
            for (int j = 0; j < newSize; j++)
            {
                if (arr[i] == arr[j])
                {
                    isDuplicate = true;
                    break;
                }
            }

            // If the current element is not a duplicate, add it to the non-duplicate section
            if (!isDuplicate)
            {
                arr[newSize] = arr[i];
                newSize++;
            }
        }

        return newSize;
    }
}

Output:

Original Array:
1 2 3 4 2 5 6 7 7 8 

Array After Removing Duplicates:
1 2 3 4 5 6 7 8 

C++

C++ offers various methods to remove duplicate elements from an Array. We will explore a simple approach using the unique() function and vectors.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    int array[] = { 1, 2, 3, 4, 2, 5, 6, 7, 7, 8 };
    int size = sizeof(array) / sizeof(array[0]);

    // Sorting the array
    std::sort(array, array + size);

    // Using unique() and vectors to remove duplicates
    std::vector<int> uniqueVector(array, array + size);
    uniqueVector.erase(std::unique(uniqueVector.begin(), uniqueVector.end()), uniqueVector.end());

    // Displaying the unique elements
    for (int element : uniqueVector) {
        std::cout << element << " ";
    }

    return 0;
}

Output:

1 2 3 4 5 6 7 8 

Code Explanation:

  • Sorting the array is crucial for the unique() function to work correctly.
  • uniqueVector holds the unique elements after removing duplicates for the Array.
  • The for loop is used to display the unique elements.

Python

Python simplifies the process with its expressive syntax. We’ll explore a method using a set to eliminate duplicates from an Array.

Method 1: Using set()

array = [1, 2, 3, 4, 2, 5, 6, 7, 7, 8]

# Using set() to remove duplicates
unique_set = set(array)

# Displaying the unique elements
for element in unique_set:
    print(element, end=" ")

Output:

1 2 3 4 5 6 7 8 

Code Explanation:

  • Python’s set() automatically removes duplicate elements.
  • The unique_set variable contains distinct elements.
  • A for loop is employed to display the unique elements.

Java

Java provides various ways to handle duplicates. We will explore a method using HashSet for efficiency.

Method 1: Using HashSet

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 2, 5, 6, 7, 7, 8};

        // Using HashSet to remove duplicates
        Set<Integer> uniqueSet = new HashSet<>();
        for (int element : array) {
            uniqueSet.add(element);
        }

        // Displaying the unique elements
        for (int element : uniqueSet) {
            System.out.print(element + " ");
        }
    }
}

Output:

1 2 3 4 5 6 7 8 

Conclusion

In conclusion, removing duplicate elements from an array is a common programming task.

Each programming language offers various approaches, and the choice depends on factors such as performance requirements and coding preferences. B

By understanding these techniques, developers can choose the most suitable method for their specific use case. 

Whether using C#, C++, Python, or Java, the goal remains consistent: to efficiently handle duplicate elements and produce clean, reliable arrays.

Recommended Articles:

Shekh Ali
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments