Open In App

Program to print all distinct elements of a given integer array in Python | Ordered Dictionary

Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted. 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, 5

Input: arr[] = {1, 1, 1, 1, 1}
Output: 1

This problem has existing solution please refer Print All Distinct Elements of a given integer array link. We will solve this problem in python quickly using Ordered Dictionary. Approach is simple,

  1. Convert array into dictionary data structure using OrderedDict.fromkeys(iterable) function, it converts any iterable into dictionary having elements as Key in the same order they appeared in array.
  2. Now iterate through complete dictionary and print keys.

Python3




# Python program to print All Distinct
# Elements of a given integer array
 
from collections import OrderedDict
 
def printDistinct(input):
     # convert list into ordered dictionary
     ordDict = OrderedDict.fromkeys(input)
 
     # iterate through dictionary and get list of keys
     # list of keys will be resultant distinct elements
     # in array
     result = [ key for (key, value) in ordDict.items() ]
 
     # concatenate list of elements with ', ' and print
     print (', '.join(map(str, result))) 
 
# Driver program
if __name__ == "__main__":
    input = [12, 10, 9, 45, 2, 10, 10, 45]
    printDistinct(input)


Output:

12, 10, 9, 45, 2

Approach#2: 

The approach of this program is to use a set to keep track of the distinct elements while iterating through the input array. Whenever a new element is encountered, it is printed and added to the set. This ensures that only the distinct elements are printed.

Algorithm

Create a set to store distinct elements.
Traverse the array from start to end.
For each element, check if it is already present in the set.
If it is not present, then add it to the set and print the element.

Python3




def distinct_elements(arr):
    distinct = set()
    for element in arr:
        if element not in distinct:
            print(element, end=' ')
            distinct.add(element)
 
arr = [12, 10, 9, 45, 2, 10, 10, 45]
distinct_elements(arr)


Output

12 10 9 45 2 

Time Complexity: O(n), where n is the length of the input array.
Auxiliary Space: O(n), where n is the length of the input array in the worst case when all elements are distinct.



Last Updated : 07 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads