Print all Unique elements in a given array

Objective: Given an array of integers which contains duplicates as well. Write a program to print all unique elements in the array. This problem is also referred as print all distinct elements in the array


[] arrA ={1, 6, 4, 3, 2, 2, 3, 8, 1};
Output: Unique elements are: 1, 6, 4, 3, 2, 8


Use Sorting-

  • Sort the array, this will bring all duplicates together.
  • Iterate through array and print all unique elements (If current element which is same as the previous element,ignore the current element).

Time Complexity: O(NlogN)

Use Hash Set

  • Create Hash Set.
  • Iterate through array, check if current element is in Hash Set, if yes then ignore the element else print the element and add it to the Hash Set.

Time Complexity: O(N), Space Complexity: O(N)

See the code below for both the approaches for better understanding.

Java Code:


Distinct Or Unique elements are (Sorting Method): 1 2 3 4 6 8
Distinct Or Unique elements are (HashSet Method): 1 2 3 4 6 8

Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

%d bloggers like this: