VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-sorted-distinct-elements-array-c/

⇱ Print sorted distinct elements of array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print sorted distinct elements of array

Last Updated : 11 Jul, 2025

Given an array that might contain duplicates, print all distinct elements in sorted order.

Examples: 

Input : 1, 3, 2, 2, 1
Output : 1 2 3
Input : 1, 1, 1, 2, 2, 3
Output : 1 2 3

The simple Solution is to sort the array first, then traverse the array and print only first occurrences of elements.

Algorithm:

  1.    Sort the given array in non-descending order.
  2.    Traverse the sorted array from left to right, and for each element do the following:
          a. If the current element is not equal to the previous element, print the current element.
          b. Otherwise, skip the current element and move on to the next one.
  3.    Stop when the end of the array is reached.

Below is the implementation of the approach:


Output
1 2 3 

Time Complexity: O(n * logn) as sort function has been called which takes O(n * logn) time. Here, n is size of the input array.

Auxiliary Space: O(1) as no extra space has been used.

Another Approach is to use set in C++ STL.  

Implementation:


Output
1 2 3 

Complexity Analysis:

  • Time Complexity: O(nlogn).
  • Auxiliary Space: O(n)
Comment
Article Tags: