text: Nearest power of 2 of nearest perfect squares of non | C ++ program for the above approach ; Function to find nearest perfect square of num ; Calculate square root of num ; Calculate perfect square ; Find the nearest perfect square ; Function to find the power of 2 nearest to the number num ; Calculate log base 2 of num ; Highest power of 2 which is <= num ; Function to find the nearest perfect square and the nearest power of 2 of every array element whose occurrence is 1 ; Stores frequency of array elements ; Traverse the array and update frequency of current array element ; Traverse the map freq ; If the frequency is 1 ; Find nearest perfect square ; Print the nearest power of 2 ; If the any does not contain any non - repeating elements ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int perfectSquare ( int num ) { int sr = sqrt ( num ) ; int a = sr * sr ; int b = ( sr + 1 ) * ( sr + 1 ) ; if ( ( num - a ) < ( b - num ) ) { return a ; } else { return b ; } } int powerOfTwo ( int num ) { int lg = log2 ( num ) ; int p = pow ( 2 , lg ) ; return p ; } void uniqueElement ( int arr [ ] , int N ) { bool ans = true ; unordered_map < int , int > freq ; for ( int i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] ] ++ ; } for ( auto el : freq ) { if ( el . second == 1 ) { ans = false ; int ps = perfectSquare ( el . first ) ; cout << powerOfTwo ( ps ) << ' ▁ ' ; } } if ( ans ) cout << " - 1" ; } int main ( ) { int arr [ ] = { 4 , 11 , 4 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; uniqueElement ( arr , N ) ; return 0 ; }