Find all good indices in the given Array | Java program to 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
import java . util . * ; class Solution { static void niceIndices ( int A [ ] , int n ) { int sum = 0 ; Map < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { m . put ( A [ i ] , ( m . get ( A [ i ] ) == null ) ? 0 : m . get ( A [ i ] ) + 1 ) ; sum += A [ i ] ; } for ( int i = 0 ; i < n ; ++ i ) { int k = sum - A [ i ] ; if ( k % 2 == 0 ) { k = k >> 1 ; if ( m . containsKey ( k ) ) { if ( ( A [ i ] == k && m . get ( k ) > 1 ) || ( A [ i ] != k ) ) System . out . print ( ( i + 1 ) + " ▁ " ) ; } } } } public static void main ( String args [ ] ) { int A [ ] = { 8 , 3 , 5 , 2 } ; int n = A . length ; niceIndices ( A , n ) ; } }