19 Apr 2024

Removing Duplicate Value from Array in Java

Removing Duplicate Value from Array in Java

In this post, we’ll explore how to remove duplicate values from an array in Java using a HashMap. The HashMap is a powerful tool for this task because it only allows unique keys, which makes it easy to filter out duplicates.

Input:

8

[2,4,6,1,7,2,4,8]

Output:

1 2 4 6 7 8

CODE

import java.util.*;

class HelloWorld {

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();

        int n=sc.nextInt();

        for(int i=0;i<n;i++){

            int temp=sc.nextInt();

            if(!map.containsKey(temp)){

                map.put(temp,1);

            }

        }

        int arr[]=new int[map.size()];

        int j=0;

        for (Map.Entry<Integer, Integer> e : map.entrySet()) 

          arr[j++]=e.getKey();

        for(int i=0;i<j;i++){

            System.out.print(arr[i]);

        }

    }

Explanation

  1. Input:

    • The program first reads the size of the array, n.
    • It then reads the array elements.
  2. Using a HashMap to Filter Duplicates:

    • A HashMap is used to store each number as a key.
    • If a number is already in the map (map.containsKey(temp)), it is ignored.
    • Otherwise, the number is added to the map with a placeholder value (e.g., 1).
  3. Creating a New Array:

    • After filtering, the unique numbers (keys of the HashMap) are transferred to a new array.
  4. Sorting the Unique Values:

    • The Arrays.sort() method is used to sort the array of unique values.
  5. Output:

    • The sorted unique values are printed.

Example Input and Output

Input:

8 2 4 6 1 7 2 4 8

Process:

  • Original Array: [2, 4, 6, 1, 7, 2, 4, 8]
  • After removing duplicates: [2, 4, 6, 1, 7, 8]
  • After sorting: [1, 2, 4, 6, 7, 8]

Output:


1 2 4 6 7 8

How This Works

  1. HashMap Filters Duplicates:

    • The HashMap automatically ensures that only unique numbers are stored as keys.
  2. Efficient Transfer:

    • The unique numbers are transferred from the HashMap to an array using a simple loop.
  3. Sorting:

    • The Arrays.sort() method sorts the array in ascending order efficiently.

Key Points

  1. Time Complexity:

    • Inserting elements into a HashMap is O(1) on average.
    • Sorting the array is O(n log n), where n is the number of unique elements.
  2. Space Complexity:

    • The HashMap and the new array require extra space proportional to the number of unique elements.
  3. Edge Cases:

    • Empty Array: If the input size n is 0, the program will produce no output.
    • All Elements Are the Same: The program will output a single element.
      • Input: [5, 5, 5, 5]
        Output: 5
  4. Sorted Output:

    • The program sorts the unique values before printing them. If sorting is not required, you can skip the Arrays.sort() step.

No comments:

Post a Comment