Home » Interview Questions » Array Interview Questions » Print all distinct elements of the array

Print all distinct elements of the array


()

ALGORITHM 1

TIME COMPLEXITY: O(N)

SPACE COMPLEXITY: O(1)

1. Simply Hash all the values and increase their count from 0 to the number of times they occur.

2. While printing we check if the count of that key is more than 0 and if yes we print it

once.

ALGORITHM 2

TIME COMPLEXITY: O(NlogN)

SPACE COMPLEXITY: O(1)

1. Use SET data structure that stores unique keys and in sorted manner.

2. Simply add all the elements and traverse the set using iterator.

#include <bits/stdc++.h>
using namespace std;

int main()
{
	int arr[]= {14,16,19,14,46,19,16,16,110};
	int N = sizeof(arr)/sizeof(arr[0]);
	
	set<int> S; // Set data structure stores unique element and  too sorted 
	
	for(int i=0;i<N;i++)
		S.insert(arr[i]);
		
	set<int> :: iterator it; //just traverse the set simply
	for(it = S.begin(); it != S.end(); it++)
		cout << *it << " ";
		
}

 

ALGORITHM 3

TIME COMPLEXITY: O(NlogN)

SPACE COMPLEXITY: O(1)

1. Sort the array.

2. Traverse the array and skip similar adjacent elements.

#include <bits/stdc++.h>
using namespace std;

int main()
{
	int arr[]= {14,16,19,14,46,19,16,16,110};
	int N = sizeof(arr)/sizeof(arr[0]);
	
	sort(arr,arr+N); // sort the array so that similar elements will occur adjacent
	
	for(int i=0;i<N;)
	{
		cout << arr[i++] << " ";
		while(arr[i] == arr[i-1] and i < N)
			i++;
	}
}

 

ALGORITHM 4

TIME COMPLEXITY: O(N 2 )

SPACE COMPLEXITY: O(1)

1. Run an outer loop to select an element.

2. Run an inner loop from start to the previous index and check if the element has occurred before.

3. If yes then don’t print it and move on to next element via outer loop.

4. Else print it and move on.

#include <bits/stdc++.h>
using namespace std;

int main()
{
	int arr[]= {14,16,19,14,46,19,16,16};
	int N = sizeof(arr)/sizeof(arr[0]);
	
	int count = 0 , j;
	
	for(int i = 0 ; i < N; i++) //select an element
	{
		for(j = 0 ; j < i; j++)//start from 0 to the previous index if the element has occured or not
			if(arr[i] == arr[j]) // if the element has occured then dont print it
				break;
				
		if(i == j)//if the element did not occur before then j will reach i and so print it.
		cout<<arr[i] << " ";
	}
}

READ  Create Maximum Number

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions