Check if an array contains only one distinct element | Java program for the above approach ; Function to find if the array contains only one distinct element ; Assume first element to be the unique element ; Traversing the array ; If current element is not equal to X then break the loop and print No ; Compare and print the result ; Driver Code ; Function call
import java . util . * ; public class Main { public static void uniqueElement ( int arr [ ] ) { int x = arr [ 0 ] ; int flag = 1 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] != x ) { flag = 0 ; break ; } } if ( flag == 1 ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 9 , 9 , 9 , 9 , 9 , 9 , 9 } ; uniqueElement ( arr ) ; } }