Find all good indices in the given Array | Function to find all good indices in the given array ; hash to store frequency of each element ; Storing frequency of each element and calculating sum simultaneously ; check if array is good after removing i - th index element ; print good indices ; Driver Code
function niceIndices ( A , n ) { var sum = 0 ; var m = new Map ( ) ; for ( var i = 0 ; i < n ; ++ i ) { if ( m . has ( A [ i ] ) ) m . set ( A [ i ] , m . get ( A [ i ] ) + 1 ) else m . set ( A [ i ] , 1 ) sum += A [ i ] ; } for ( var i = 0 ; i < n ; ++ i ) { var k = sum - A [ i ] ; if ( k % 2 == 0 ) { k = k >> 1 ; if ( m . has ( k ) ) { if ( ( A [ i ] == k && m . get ( k ) > 1 ) || ( A [ i ] != k ) ) document . write ( i + 1 + " " ) ; } } } } var A = [ 8 , 3 , 5 , 2 ] ; var n = A . length ; niceIndices ( A , n ) ;