Program to print all distinct elements of a given integer array in Python | Ordered Dictionary
Last Updated :
07 Apr, 2023
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,
- 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.
- Now iterate through complete dictionary and print keys.
Python3
from collections import OrderedDict
def printDistinct( input ):
ordDict = OrderedDict.fromkeys( input )
result = [ key for (key, value) in ordDict.items() ]
print ( ', ' .join( map ( str , result)))
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)
|
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.
Share your thoughts in the comments
Please Login to comment...