Be the first user to complete this post

  • 0
Add to List
Beginner

340. 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

Example:

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

Approach:

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.

Output:

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