Remove Duplicates from an Array

Problem Statement:

Create a Java program to remove duplicates from an array.

Input:

An array of integers arr.

Example:

Input: [1, 2, 3, 2, 4, 3, 5]
Output: [1, 2, 3, 4, 5]

Step-by-Step Solution:

Step 1: Use a Set to Track Unique Elements

  • Utilize a HashSet to store unique elements from the array. Sets automatically handle duplicate values.
Set<Integer> uniqueElements = new HashSet<>();

Step 2: Add Elements to the Set

  • Iterate through the array and add each element to the HashSet. Duplicates will be ignored by the Set.
for (int num : arr) {
    uniqueElements.add(num);
}

Step 3: Convert the Set Back to an Array

  • Convert the HashSet back to an array for the final result.
Integer[] resultArray = uniqueElements.toArray(new Integer[0]);

Complete Solution:

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

public class RemoveDuplicates {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 4, 3, 5};
        int[] result = removeDuplicates(arr);

        System.out.print("Array without duplicates: ");
        for (int num : result) {
            System.out.print(num + " ");
        }
    }

    public static int[] removeDuplicates(int[] arr) {
        // Step 1: Use a Set to track unique elements
        Set<Integer> uniqueElements = new HashSet<>();

        // Step 2: Add elements to the Set
        for (int num : arr) {
            uniqueElements.add(num);
        }

        // Step 3: Convert Set back to an array
        Integer[] resultArray = uniqueElements.toArray(new Integer[0]);

        // Convert Integer[] to int[]
        int[] result = new int[resultArray.length];
        for (int i = 0; i < resultArray.length; i++) {
            result[i] = resultArray[i];
        }

        return result;
    }
}

Explanation:

  • Use of Set: A HashSet is used because it does not allow duplicate values and provides efficient insertion and lookup.
  • Conversion to Array: After removing duplicates, convert the HashSet back to an array to match the expected output format.

Example:

int[] arrayWithDuplicates = {1, 1, 2, 3, 3, 4};
int[] uniqueArray = removeDuplicates(arrayWithDuplicates);
System.out.println(Arrays.toString(uniqueArray)); // Output: [1, 2, 3, 4]

This program demonstrates how to efficiently remove duplicate values from an array using Java’s HashSet.