Unique element in an array where all elements occur K times except one | Set 2 | Java program for the above approach ; Function that find the unique element in the array arr [ ] ; Store all unique element in set ; Sum of all element of the array ; Sum of element in the set ; Print the unique element using formula ; Driver code ; Function call
import java . util . * ; class GFG { static void findUniqueElements ( int arr [ ] , int N , int K ) { Set < Integer > s = new HashSet < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) s . add ( arr [ i ] ) ; int arr_sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) arr_sum += arr [ i ] ; int set_sum = 0 ; Iterator it = s . iterator ( ) ; while ( it . hasNext ( ) ) { set_sum += ( int ) it . next ( ) ; } System . out . println ( ( K * set_sum - arr_sum ) / ( K - 1 ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 } ; int N = arr . length ; int K = 3 ; findUniqueElements ( arr , N , K ) ; } }