VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-distinct-elements-given-integer-array/

⇱ Diistinct elements in a given array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Diistinct elements in a given array

Last Updated : 29 Apr, 2026

Given an array arr[] of integers which may or may not contain duplicate elements. Your task is to remove duplicate elements. Your result should have elements according their first appearance in the input array.

Examples:

Input: arr[] = [1, 2, 3, 1, 4, 2]
Output: [1, 2, 3, 4]
Explanation: 2 and 1 have more than 1 occurence.

Input: arr[] = [1, 2, 3, 4]
Output: [1, 2, 3, 4]
Explanation: There is no duplicate element.

[Naive Approach] Using Nested loops - O(n^2) Time and O(1) Space

Use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on left side of it. If present, then ignore the element, else store it in result.


Output
1 2 3 4 

[Expected Approach] Using Hash Set - O(n) Time and O(n) Space

Use Hash Set to store distinct element. Insert all the elements in a hash set and then traverse the hash set to store the distinct elements in the resultant array.

  • Create an empty hash set to store unique elements.
  • Create a result vector to store the final answer.
  • Traverse the given array from left to right. For each element, check if it is present in the set.
  • If not present, insert it into the set and add it to the result vector.
  • Return the result vector containing only unique elements.

Output
1 2 3 4 
Comment