Check if an array contains only one distinct element | C ++ program for the above approach ; Function to find if the array contains only one distinct element ; Create a set ; Traversing the array ; Compare and print the result ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void uniqueElement ( int arr [ ] , int n ) { unordered_set < int > set ; for ( int i = 0 ; i < n ; i ++ ) { set . insert ( arr [ i ] ) ; } if ( set . size ( ) == 1 ) { cout << " YES " << endl ; } else { cout << " NO " << endl ; } } int main ( ) { int arr [ ] = { 9 , 9 , 9 , 9 , 9 , 9 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; uniqueElement ( arr , n ) ; return 0 ; }