Introduction
In the blog, we will look at the problem statement to print all distinct elements of a given integer array. The output for this problem should print each entry only once because the specified array can include duplicates. The array being used is not ordered(or sorted).
Example for Sample Input and Output
Sample Input | Sample Output |
Arr[]={12,3,31,12,32,32} | 12 3 31 32 |
Arr[]={7,3,5,1,7,5,34} | 7 3 5 1 34 |
Approach 1: Brute Force
Check each element to see if there is another element that is present that has the same value as the current element but a lower index. Print the current element if there isn't one; otherwise, skip it if it is absent.
Algorithm
-
Run a loop from ‘0’ to ‘n-1’ for integer ‘i’.
-
Run a for ‘j; loop from ‘0’ to ‘i’.
- Print Arr[i] if j==i.
- Break out of this loop if Arr[i] === Arr[j].
- Return.
-
Run a for ‘j; loop from ‘0’ to ‘i’.
C++ Implementation
/*
Print all distinct elements of a given integer array
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Input the array size"<<endl;
cin>>n;
vector<int> Arr(n);
cout<<"Input the integers in the array:"<<endl;
for(int i=0;i<n;i++)
{
cin>>Arr[i];
}
cout<<"The distinct elements of the array are: ";
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
if(j==i)
{
cout<<Arr[j]<<" ";
}
if(Arr[i]==Arr[j])
{
break;
}
}
}
return 0;
}
Output
Java Implementation
/*
Print all distinct elements of a given integer array
*/
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input the array size");
int n = sc.nextInt();
int[] Arr = new int[n];
System.out.println("Input the integers in the array:");
for(int i=0;i<n;i++)
{
Arr[i] = sc.nextInt();;
}
System.out.print("The distinct elements of the array are: ");
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
if(j==i)
{
System.out.print(Arr[i]+" ");
}
if(Arr[i]==Arr[j])
{
break;
}
}
}
}
}
Output
Python Implementation
#Print all distinct elements of a given integer array
def printAllDistinctEle(Arr, n):
print("The distinct elements of the array are:",end=" ")
for i in range(0, n):
d = 0
for j in range(0, i):
if (Arr[i] == Arr[j]):
d = 1
break
if (d == 0):
print(Arr[i],end=" ")
Arr = []
n = int(input("Input the array size\n"))
print("Input the integers in the array:")
for i in range(0, n):
ele = int(input())
Arr.append(ele)
printAllDistinctEle(Arr, n)
Output
Complexity Analysis
Time Complexity
Each of our two nested loops is of size ‘N’, the time complexity is therefore O(N2).
Space Complexity
The space complexity is O(1) because we haven't used any additional space.
Check out this array problem - Merge 2 Sorted Arrays