Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Print all Distinct (Unique) Elements in given Array
Next article icon

Print sorted distinct elements of array

Last Updated : 11 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

C++




// CPP program to print sorted distinct
// elements.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print sorted distinct
// elements
void printDistinct(int arr[], int n) {
    // Sort the array
    sort(arr, arr + n);
 
    // Traverse the sorted array
    for (int i = 0; i < n; i++) {
 
        // If the current element is not equal to the previous
        // element, print it
        if (i == 0 || arr[i] != arr[i - 1])
            cout << arr[i] << " ";
    }
}
 
// Driver's code
int main() {
      // Input array
    int arr[] = { 1, 3, 2, 2, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
   
      // Function call
    printDistinct(arr, n);
   
    return 0;
}
 
 

Java




// Java program to print sorted distinct
// elements.
 
import java.util.*;
 
class GFG {
    // Function to print sorted distinct
    // elements
    static void printDistinct(int arr[], int n) {
        // Sort the array
        Arrays.sort(arr);
       
        // Traverse the sorted array
        for (int i = 0; i < n; i++) {
            // If the current element is not equal to the
            // previous element, print it
            if (i == 0 || arr[i] != arr[i - 1])
                System.out.print(arr[i] + " ");
        }
    }
 
    // Driver's code
    public static void main(String[] args) {
        // Input array
        int arr[] = { 1, 3, 2, 2, 1 };
        int n = arr.length;
 
        // Function call
        printDistinct(arr, n);
    }
}
 
 

Python3




# Python program to print sorted distinct elements
def printDistinct(arr):
    # Sort the array
    arr.sort()
 
    # Traverse the sorted array
    for i in range(len(arr)):
 
        # If the current element is not equal to the previous
        # element, print it
        if i == 0 or arr[i] != arr[i - 1]:
            print(arr[i])
 
# Driver code
arr = [1, 3, 2, 2, 1]
printDistinct(arr)
 
 

C#




using System;
using System.Linq;
 
class GFG {
    // Function to print sorted distinct elements
    static void printDistinct(int[] arr, int n) {
        // Sort the array
        Array.Sort(arr);
 
        // Traverse the sorted array
        for (int i = 0; i < n; i++) {
            // If the current element is not equal to the previous element, print it
            if (i == 0 || arr[i] != arr[i - 1])
                Console.Write(arr[i] + " ");
        }
    }
 
    // Driver's code
    public static void Main() {
        // Input array
        int[] arr = { 1, 3, 2, 2, 1 };
        int n = arr.Length;
 
        // Function call
        printDistinct(arr, n);
    }
}
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL
 
 

Javascript




// Javascript program to print sorted distinct
// elements.
function printDistinct(arr) {
    // Sort the array
    arr.sort((a, b) => a - b);
 
    // Traverse the sorted array
    for (let i = 0; i < arr.length; i++) {
 
        // If the current element is not equal to the previous
        // element, print it
        if (i === 0 || arr[i] !== arr[i - 1]) {
            console.log(arr[i]);
        }
    }
}
 
// Driver code
const arr = [1, 3, 2, 2, 1];
printDistinct(arr);
 
 
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:

C++




// CPP program to print sorted distinct
// elements.
#include <bits/stdc++.h>
using namespace std;
 
void printRepeating(int arr[], int size)
{
    // Create a set using array elements
    set<int> s(arr, arr + size);
 
    // Print contents of the set.
    for (auto x : s)
        cout << x << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 1, 3, 2, 2, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, n);
    return 0;
}
 
 

Java




// Java program to print sorted distinct
// elements.
import java.io.*;
import java.util.*;
 
public class GFG {
      
    static void printRepeating(Integer []arr, int size)
    {
        // Create a set using array elements
        SortedSet<Integer> s = new TreeSet<>();
        Collections.addAll(s, arr);
         
        // Print contents of the set.
        System.out.print(s);
    }
      
    // Driver code
    public static void main(String args[])
    {
        Integer []arr = {1, 3, 2, 2, 1};
        int n = arr.length;
        printRepeating(arr, n);
    }
}
  
// This code is contributed by
// Manish Shaw (manishshaw1)
 
 

Python3




# Python3 program to print
# sorted distinct elements.
 
def printRepeating(arr,size):
 
    # Create a set using array elements
    s = set()
    for i in range(size):
        if arr[i] not in s:
            s.add(arr[i])
 
    # Print contents of the set.
    for i in s:
        print(i,end=" ")
 
# Driver code
if __name__=='__main__':
    arr = [1,3,2,2,1]
    size = len(arr)
    printRepeating(arr,size)
 
# This code is contributed by
# Shrikant13
 
 

C#




// C# program to print sorted distinct
// elements.
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG {
     
    static void printRepeating(int []arr, int size)
    {
        // Create a set using array elements
        SortedSet<int> s = new SortedSet<int>(arr);
     
        // Print contents of the set.
        foreach (var n in s)
        {
            Console.Write(n + " ");
        }
    }
     
    // Driver code
    public static void Main()
    {
        int []arr = {1, 3, 2, 2, 1};
        int n = arr.Length;
        printRepeating(arr, n);
    }
}
 
// This code is contributed by
// Manish Shaw (manishshaw1)
 
 

Javascript




<script>
 
// Javascript program to print sorted distinct
// elements.
function printRepeating(arr, size)
{
     
    // Create a set using array elements
    var s = new Set(arr);
 
    // Print contents of the set.
    [...s].sort((a, b) => a - b).forEach(x => {
        document.write(x + " ")
    });
}
 
// Driver code
var arr = [ 1, 3, 2, 2, 1 ];
var n = arr.length;
 
printRepeating(arr, n);
 
// This code is contributed by itsok
 
</script>
 
 
Output
1 2 3       

Complexity Analysis:

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


Next Article
Print all Distinct (Unique) Elements in given Array

A

Anivesh Tiwari
Improve
Article Tags :
  • Arrays
  • DSA
  • Sorting
  • cpp-set
Practice Tags :
  • Arrays
  • Sorting

Similar Reads

  • Print all Distinct (Unique) Elements in given Array
    Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2} Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4
    11 min read
  • Product of non-repeating (distinct) elements in an Array
    Given an integer array with duplicate elements. The task is to find the product of all distinct elements in the given array. Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10}; Output : 97200 Here we take 12, 10, 9, 45, 2 for product because these are the only distinct elements Input : arr
    15 min read
  • Print uncommon elements from two sorted arrays
    Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements ar
    6 min read
  • Count distinct elements in an array in Python
    Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
    2 min read
  • Count Distinct ( Unique ) elements in an array
    Given an array arr[] of length N, The task is to count all distinct elements in arr[]. Examples:  Input: arr[] = {10, 20, 20, 10, 30, 10}Output: 3Explanation: There are three distinct elements 10, 20, and 30. Input: arr[] = {10, 20, 20, 10, 20}Output: 2 Naïve Approach: Create a count variable and ru
    15 min read
  • Distinct adjacent elements in an array
    Given an array, find whether it is possible to obtain an array having distinct neighbouring elements by swapping two neighbouring array elements. Examples: Input : 1 1 2 Output : YES swap 1 (second last element) and 2 (last element), to obtain 1 2 1, which has distinct neighbouring elements . Input
    7 min read
  • Find sum of non-repeating (distinct) elements in an array
    Given an integer array with repeated elements, the task is to find the sum of all distinct elements in the array.Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};Output : 78Here we take 12, 10, 9, 45, 2 for sumbecause it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4}
    14 min read
  • Counting Distinct elements after Range of Operations
    Given an integer K and array A[] of size N, count the number of distinct elements after performing an operation on every array index. For each i (0 ≤ i ≤ N - 1), we can perform one of the following operations exactly once: Add K to A[i]Subtract K from A[i]Leave A[i] as it is.Examples: Input: N = 6,
    7 min read
  • Making elements distinct in a sorted array by minimum increments
    Given a sorted integer array. We need to make array elements distinct by increasing values and keeping array sum minimum possible. We need to print the minimum possible sum as output. Examples: Input : arr[] = { 2, 2, 3, 5, 6 } ; Output : 20 Explanation : We make the array as {2, 3, 4, 5, 6}. Sum be
    10 min read
  • Find the only different element in an array
    Given an array of integers where all elements are same except one element, find the only different element in the array. It may be assumed that the size of the array is at least two.Examples: Input : arr[] = {10, 10, 10, 20, 10, 10} Output : 3 arr[3] is the only different element.Input : arr[] = {30
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences