How to find unique elements in an array in Java

So firstly we will learn about what is an array and how we can define it in java. Later we will see a program on how to find unique elements in an array in Java.

An array is a data structure that is used to store data of the same datatype. Users can explicitly take the value of size or have to define it in the program before using it.

An array is useful in many ways one such example is if the user wants to store many numbers of the same datatype then he can do that by defining an array and not explicitly defining each number.

Syntax:

datatype[] arrayname;
or
datatype arrayname[];

Find unique elements in an array in Java

The easy approach to solve this problem is by using the Naive Method.

import java.util.Scanner;
import java. util. Arrays;


public class uniqueElement {

 public static void main(String[] args) {

      Scanner sc = new Scanner(System.in);

      System.out.println("Enter the size of the array 1:");
      int size1 = sc.nextInt();

      int[] arrayEx1 = new int[size1];
      System.out.println("Enter the elements of the array1:");
  
      for(int i=0; i<arrayEx1.length; i++) {
         arrayEx1[i] = sc.nextInt();
      }

    Arrays.sort(arrayEx1);     
    for (int i=0;i<arrayEx1.length;i++)
    System.out.println(arrayEx1[i]);
    int i=0;
    System.out.println("Unique Elements in array:");
    while(i<arrayEx1.length)
    {
        if(arrayEx1[i]!=arrayEx1[i+1])
        {
            System.out.println(arrayEx1[i]);
        }
        i=i+2;
    }
}
}

Explanation:

Here we have taken array size and elements from the user. The logic here applied is first we sort the array using java in build function Arrays.sort(). Then we take the first element from the array and check with the rightmost element if it is not equal then the element is unique else not. The complexity here is o(nlogn) as the logn complexity is for sorting.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *